Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bubble-sort.js #7

Open
AliSalman86 opened this issue Feb 1, 2017 · 1 comment
Open

bubble-sort.js #7

AliSalman86 opened this issue Feb 1, 2017 · 1 comment

Comments

@AliSalman86
Copy link

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
Copy link

cagmz commented Feb 28, 2017

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants