Javascript: Bubble Sort

Kabir Shah picture Kabir Shah · Jun 14, 2016 · Viewed 24.8k times · Source

I have made a bubble sort algorithm (sorta) using JS. It works sometimes, but the problem is that it only iterates through the array once. Here is my code:

function bubble(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] > arr[i + 1]) {
      var a = arr[i]
      var b = arr[i + 1]
      arr[i] = b
      arr[i + 1] = a
    }
  }
  return arr;
}

Answer

Amir Popovich picture Amir Popovich · Jun 14, 2016

You need an inner loop to complete the sort correctly:

function bubble(arr) {
      var len = arr.length;
    
      for (var i = 0; i < len ; i++) {
        for(var j = 0 ; j < len - i - 1; j++){ // this was missing
        if (arr[j] > arr[j + 1]) {
          // swap
          var temp = arr[j];
          arr[j] = arr[j+1];
          arr[j + 1] = temp;
        }
       }
      }
      return arr;
    }

document.write(bubble([1,9,2,3,7,6,4,5,5]));