Created
May 4, 2021 15:42
-
-
Save Neo42/27754b383e75a88f83084f6cb062c003 to your computer and use it in GitHub Desktop.
Hoare's quicksort. More performant than Lomuto's.
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 quickSort = (arr, low = 0, high = arr.length - 1) => { | |
if (low < high) { | |
const p = partition(arr, low, high) | |
quickSort(arr, low, p) | |
quickSort(arr, p + 1, high) | |
} | |
} | |
const partition = (arr, low, high) => { | |
const pivot = arr[Math.floor((high + low) / 2)] | |
let i = low | |
let j = high | |
while (true) { | |
while (arr[i] < pivot) { | |
i++ | |
} | |
while (arr[j] > pivot) { | |
j-- | |
} | |
if (i >= j) { | |
return j | |
} | |
;[arr[i], arr[j]] = [arr[j], arr[i]] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment