Skip to content

Instantly share code, notes, and snippets.

@nodew
Last active February 27, 2019 05:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nodew/13f2efbf7336abc265ac10e60c195953 to your computer and use it in GitHub Desktop.
Save nodew/13f2efbf7336abc265ac10e60c195953 to your computer and use it in GitHub Desktop.
bubbleSort implementation
const defaultCompare = (a, b) => a < b;
const swapArrayItem = (arr, i, j) => {
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
};
const bubbleSort = (arr, compare = defaultCompare) => {
let len = arr.length;
let swapped;
do {
swapped = false;
for (let i = 0; i < len - 1; i++) {
if (!compare(arr[i], arr[i + 1])) {
swapArrayItem(arr, i, i + 1)
swapped = true;
}
}
len -= 1;
} while (swapped)
return arr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment