Created
July 22, 2016 20:36
-
-
Save sabotuer99/55f481ea5a75fc894ca87a5ae0bdcb8d to your computer and use it in GitHub Desktop.
quicksort in javascript
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
//http://blog.mgechev.com/2012/11/24/javascript-sorting-performance-quicksort-v8/ | |
function swap(array, i, j) { | |
var temp = array[i]; | |
array[i] = array[j]; | |
array[j] = temp; | |
return array; | |
} | |
function partition(array, left, right, comparitor) { | |
var cmp = array[right - 1], | |
minEnd = left, | |
maxEnd; | |
for (maxEnd = left; maxEnd < right - 1; maxEnd += 1) { | |
//if (array[maxEnd] <= cmp) { | |
if (comparitor(array[maxEnd], cmp) <= 0) { | |
swap(array, maxEnd, minEnd); | |
minEnd += 1; | |
} | |
} | |
swap(array, minEnd, right - 1); | |
return minEnd; | |
} | |
function quickSort(array, left, right, comparitor) { | |
if (left < right) { | |
var p = partition(array, left, right, comparitor); | |
quickSort(array, left, p, comparitor); | |
quickSort(array, p + 1, right, comparitor); | |
} | |
return array; | |
} | |
//don't use, native sort is 4x faster | |
function qs(array, comparitor) { | |
return quickSort(array, 0, array.length, comparitor); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment