Skip to content

Instantly share code, notes, and snippets.

@lopezm1
Created May 20, 2018 21:56
Show Gist options
  • Save lopezm1/e7959225dcc6e3bd1bc4e787ba873898 to your computer and use it in GitHub Desktop.
Save lopezm1/e7959225dcc6e3bd1bc4e787ba873898 to your computer and use it in GitHub Desktop.
function bubbleSort(arr) {
var hasSwapped = true;
while(hasSwapped){
hasSwapped = false; // attempt to be done
for(var i = 0; i < arr.length - 1; i++){
var tmp;
if(arr[i+1] < arr[i]) { //if value ahead of it is smaller
console.log("Before", arr)
tmp = arr[i+1]; // hold value
arr[i+1] = arr[i];
arr[i] = tmp; // swap values
console.log("After", arr)
hasSwapped = true; // one more loop
}
}
}
}
bubbleSort([5, 1, 4, 2, 8])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment