Created
August 7, 2017 17:20
-
-
Save JustinBeaudry/296062ecf2ebf4203b2024a8f689f4f4 to your computer and use it in GitHub Desktop.
Quick Sort with Hoare Partitioning
This file contains hidden or 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 _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