Bubble Sort

You could honestly use any sorting method you could find but we'll start with Bubble Sort.

Completed Code

function bubbleSort(arr){
    var len = arr.length;
    for (var i = len-1; i>=0; i--){
        for( j = 1; j<=i; j++){
            if(arr[j-1]>arr[j]){
                var temp = arr[j-1];
                arr[j-1] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}
console.log(bubbleSort([207, 150, 71, -25, 369, 246, -13, 22, 150]));

We already know the output is [ -25, -13, 22, 71, 150, 150, 207, 246, 369 ] but how did bubbleSort() get there?

Explanation

  1. bubbleSort compares the first two elements.

  2. 207 > 150, they switch places.

  3. The process is repeated with the next element, 207 is compared to 71.

  4. We switch our comparison number when 207 gets to 369. 369 is larger, so it moves on.

  5. The process stops when we reach the last element in our array. The highest value 369 has "bubbled up" to the top.

  6. We move backwards down the array repeating the process, starting with the comparison of 369 and 150.

  7. After the first full cycle, when it reaches the start of the array again, it should look like [ -25, 150, 71, -13, 207, 246, 22, 150, 369]

  8. We repeat the process until the array has been properly sorted.

Last updated