Skip to content

Instantly share code, notes, and snippets.

@YozhEzhi
Last active April 23, 2017 13:20
Show Gist options
  • Save YozhEzhi/99799ad9ceaccf2d9673e8b1a90e220e to your computer and use it in GitHub Desktop.
Save YozhEzhi/99799ad9ceaccf2d9673e8b1a90e220e to your computer and use it in GitHub Desktop.
Bubble Sort
/**
* Helper function to swap items in array
*/
function swap(arr, firstIndex, secondIndex) {
const temp = arr[firstIndex];
arr[firstIndex] = arr[secondIndex];
arr[secondIndex] = temp;
}
/**
* For loop variant
*/
function bubbleSort(arr) {
let len = arr.length;
let i, j, stop;
for (i = 0; i < len; i++){
for (j = 0, stop = len - i; j < stop; j++){
if (arr[j] > arr[j + 1]) swap(arr, j, j + 1);
}
}
return arr;
}
/**
* While loop variant
*/
function bubbleSort(arr) {
let i = 0;
while (i < arr.length) {
if (arr[i] > arr[i + 1]) {
swap(arr, i, i + 1);
i = 0;
} else {
i++;
}
}
return arr;
}
console.log(bubbleSort([3, 2, 1, 3])); // [1, 2, 3, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment