Skip to content

Instantly share code, notes, and snippets.

@fed
Created August 31, 2017 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fed/39f5ee62208110756b2ffb3ab8095f64 to your computer and use it in GitHub Desktop.
Save fed/39f5ee62208110756b2ffb3ab8095f64 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