Last active
February 27, 2019 05:46
-
-
Save nodew/13f2efbf7336abc265ac10e60c195953 to your computer and use it in GitHub Desktop.
bubbleSort implementation
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
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