Skip to content

Instantly share code, notes, and snippets.

@zendzo
Forked from fed/bubble-sort.js
Created October 17, 2018 04:14
Show Gist options
  • Save zendzo/6c2dfe50de0a98563bf0c3aede34e649 to your computer and use it in GitHub Desktop.
Save zendzo/6c2dfe50de0a98563bf0c3aede34e649 to your computer and use it in GitHub Desktop.
Bubble Sort
const numbers = [13, 5, -3, 7, 6, 4, 1, 17, 0, -1, -2];
function sort(arr) {
const sorted = arr.slice();
let swapped;
do {
swapped = false;
for (let i = 0, l = sorted.length; i < l; i++) {
if (sorted[i] > sorted[i + 1]) {
const temp = sorted[i];
sorted[i] = sorted[i + 1];
sorted[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
return sorted;
}
console.log(sort(numbers));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment