computer-science-in-javascript icon indicating copy to clipboard operation
computer-science-in-javascript copied to clipboard

bubble-sort.js

Open AliSalman86 opened this issue 8 years ago • 1 comments

is there a known issue for sorting when there is 0 in the array, I used a code similar to the one that you used in bubble-sort.js , but whenever I add 0 to the array it stays in same position and sorting starts after the 0

var array = [4, 7, 0, 5, 1, 3, 6, 2, 9, 8, 10, 13, 15, 12, 14, 11];

the result sorted array would be [ 4, 7, 0, 1, 2, 3, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15 ]

AliSalman86 avatar Feb 01 '17 04:02 AliSalman86

I think this is the offending line:

if(array[i] && array[i + 1] && array[i] > array[i + 1])

array[i] is falsey if the element at i is 0.

function bubbleSort(array) {
  var swapped;
  do {
    swapped = false;
    for(var i = 0; i < array.length; i++) {
      if(array[i] > array[i + 1]) {
        swap(array, i, i + 1);
        swapped = true;
      }
    }
  } while(swapped);
  return array;
}

cagmz avatar Feb 28 '17 02:02 cagmz