Skip to content

Instantly share code, notes, and snippets.

@kshirish
Created August 12, 2024 04:25
Show Gist options
  • Save kshirish/1828b05ab595c46b6d3ec021ca803c1e to your computer and use it in GitHub Desktop.
Save kshirish/1828b05ab595c46b6d3ec021ca803c1e to your computer and use it in GitHub Desktop.
function bubbleSort(arr) {
for(let i = 0; i < arr.length - 1; i += 1) { // how many times
let swapped = false;
for(let j = 0; j < arr.length - 1 - i; j += 1) { // till where
if(arr[j + 1] < arr[j]) {
[arr[j + 1], arr[j]] = [arr[j], arr[j + 1]];
swapped = true;
}
}
if(!swapped) {
break;
}
}
return arr;
}
console.log(bubbleSort([2, 8, 10, 4, 3, 6, 7]));
console.log(bubbleSort([7, 3, 9, 12, 11]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment