Last active
December 14, 2017 08:47
-
-
Save alexnoz/a9126617453328ca7b8d104187205b98 to your computer and use it in GitHub Desktop.
The 'quicksort' algorithm implemented using Hoare's partition scheme
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
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