Created
May 20, 2018 21:56
-
-
Save lopezm1/e7959225dcc6e3bd1bc4e787ba873898 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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