Skip to content

Instantly share code, notes, and snippets.

@danielrohers
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielrohers/8ce8c7fcb68f50e7960f to your computer and use it in GitHub Desktop.
Save danielrohers/8ce8c7fcb68f50e7960f to your computer and use it in GitHub Desktop.
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