Skip to content

Instantly share code, notes, and snippets.

@karuna24s
Created February 11, 2018 14:21
Show Gist options
  • Save karuna24s/68cd0810c5068806668cb23d5e559148 to your computer and use it in GitHub Desktop.
Save karuna24s/68cd0810c5068806668cb23d5e559148 to your computer and use it in GitHub Desktop.
const array = [2, 5, 4, 3, 1];
function bubbleSort(array) {
let swapped;
do {
swapped = false;
for(let i = 0; i < array.length; i++) {
if(array[i] && array[i + 1] && array[i] > array[i + 1]) {
[array[i], array[i + 1]] = [array[i + 1], array[i]];
swapped = true;
}
}
} while(swapped);
return array;
}
console.log(bubbleSort(array.slice())); // => [ 1, 2, 3, 4, 5 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment