Skip to content

Instantly share code, notes, and snippets.

@vaidehijoshi
Created May 29, 2017 05:23
Show Gist options
  • Save vaidehijoshi/7c9185a265be7de6e879e83452a734d5 to your computer and use it in GitHub Desktop.
Save vaidehijoshi/7c9185a265be7de6e879e83452a734d5 to your computer and use it in GitHub Desktop.
function bubbleSort(array) {
var isSorted = false;
while (!isSorted) {
isSorted = true;
// Iterate until we get to the last element
for (var index = 1; index < array.length; index++) {
console.log("comparing " + array[index] + " and " + array[index - 1]);
// If the element to the left is bigger, then swap the element
// that we're currently looking at with its left neighbor.
if (array[index - 1] > array[index]) {
isSorted = false;
console.log("SWAPPING " + array[index] + " and " + array[index - 1]);
// Swap elements by creating a temporary reference.
var temporaryReference = array[index - 1];
array[index - 1] = array[index];
array[index] = temporaryReference;
}
console.log('array is now ', array);
}
console.log("**one full pass through array**");
console.log("***is array sorted? ", isSorted);
}
return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment