benoitvallon/computer-science-in-javascript

bubble-sort.js

AliSalman86 opened this issue · 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 ]

cagmz commented

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;
}