Skip to content

bubble-sort.js #7

Open
Open
@AliSalman86

Description

@AliSalman86

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 ]

Activity

cagmz

cagmz commented on Feb 28, 2017

@cagmz

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      bubble-sort.js · Issue #7 · benoitvallon/computer-science-in-javascript