Last active
August 29, 2015 14:24
-
-
Save danielrohers/8ce8c7fcb68f50e7960f to your computer and use it in GitHub Desktop.
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
var quickSort = function(arr, key, reverse) { | |
reverse = reverse || false | |
if (arr.length <= 1) { | |
return arr; | |
} | |
var less = Array(), | |
greater = Array(); | |
var pivotIndex = Math.floor(arr.length / 2); | |
var pivot = arr.splice(pivotIndex, 1)[0]; | |
for (var x = 0; x < arr.length; x++) { | |
if ( | |
(!key && !reverse && ( (arr[x] < pivot) || (arr[x] == pivot && x < pivotIndex) )) || | |
(key && !reverse && ( (arr[x][key] < pivot[key]) || (arr[x][key] == pivot[key] && x < pivotIndex) )) || | |
(!key && reverse && ( (arr[x] > pivot) || (arr[x] == pivot && x > pivotIndex) )) || | |
(key && reverse && ( (arr[x][key] > pivot[key]) || (arr[x][key] == pivot[key] && x > pivotIndex) )) ) { | |
less.push(arr[x]); | |
} else { | |
greater.push(arr[x]); | |
} | |
} | |
return quickSort(less, key).concat([pivot], quickSort(greater, key)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment