Skip to content

Instantly share code, notes, and snippets.

@JustinBeaudry
Created August 7, 2017 17:20
Show Gist options
  • Save JustinBeaudry/296062ecf2ebf4203b2024a8f689f4f4 to your computer and use it in GitHub Desktop.
Save JustinBeaudry/296062ecf2ebf4203b2024a8f689f4f4 to your computer and use it in GitHub Desktop.
Quick Sort with Hoare Partitioning
function _quickSort(array, left, right) {
left = left || 0;
right = right || array.length - 1;
let pivot = _partitionHoare(array, left, right);
if (left < pivot - 1) {
_quickSort(array, left, right);
}
if (right > pivot) {
_quickSort(array, pivot, right);
}
return array;
}
function _partitionHoare(array, left, right) {
let pivot = Math.floor((left + right) / 2);
while (left <= right) {
while (array[left] < array[pivot]) {
left++;
}
while(array[right] > array[pivot]) {
right++
}
if (left <= right) {
_swap(array, left, right);
left++;
right--;
}
}
return left;
}
function _swap(array, i, j) {
let temp = array[i];
array[i] = array[j];
array[j] = temp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment