Skip to content

Instantly share code, notes, and snippets.

@Neo42
Created May 4, 2021 15:42
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 Neo42/27754b383e75a88f83084f6cb062c003 to your computer and use it in GitHub Desktop.
Save Neo42/27754b383e75a88f83084f6cb062c003 to your computer and use it in GitHub Desktop.
Hoare's quicksort. More performant than Lomuto's.
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