Skip to content

Instantly share code, notes, and snippets.

@alexnoz
Last active December 14, 2017 08:47
Show Gist options
  • Save alexnoz/a9126617453328ca7b8d104187205b98 to your computer and use it in GitHub Desktop.
Save alexnoz/a9126617453328ca7b8d104187205b98 to your computer and use it in GitHub Desktop.
The 'quicksort' algorithm implemented using Hoare's partition scheme
function swap(arr, i, j) {
const temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
function quickSort (arr) {
function partition (lo, hi) {
const p = arr[Math.floor((lo + hi) / 2)]
let i = lo - 1
let j = hi + 1
while (true) {
do i++
while (arr[i] < p)
do j--
while (arr[j] > p)
if (i >= j) return j
swap(arr, i, j)
}
}
function sort (lo, hi) {
if (lo < hi) {
const p = partition(lo, hi)
sort(lo, p)
sort(p + 1, hi)
}
}
sort(0, arr.length - 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment