Skip to content

Instantly share code, notes, and snippets.

@venil7
Last active August 29, 2015 14:20
Show Gist options
  • Save venil7/0c32556fe31e8d60d628 to your computer and use it in GitHub Desktop.
Save venil7/0c32556fe31e8d60d628 to your computer and use it in GitHub Desktop.
quick sort
var array = [1, 7, 5, 9, 0, 4, 12, -56, 7, 0, -45, 8, 2, 3, 6, 7, 8, 1, 5, 0, 1, 7, 5, 9, 0, 4, 12, -56, 7, 0, -45, 8, 2, 3, 6, 7, 8, 1, 5, 0, 1, 7, 5, 9, 0, 4, 12, -56, 7, 0, -45, 8, 2, 3, 6, 7, 8, 1, 5, 0, 1, 7, 5, 9, 0, 4, 12, -56, 7, 0, -45, 8, 2, 3, 6, 7, 8, 1, 5, 0, 1, 7, 5, 9, 0, 4, 12, -56, 7, 0, -45, 8, 2, 3, 6, 7, 8, 1, 5, 0, 1, 7, 5, 9, 0, 4, 12, -56, 7, 0, -45, 8, 2, 3, 6, 7, 8, 1, 5, 0, 1, 7, 5, 9, 0, 4, 12, -56, 7, 0, -45, 8, 2, 3, 6, 7, 8, 1, 5, 0];
var getRandomInt = function (min, max) {
return Math.floor(Math.random() * (max - min)) + min;
};
var quick_sort = function (unsorted) {
if (unsorted.length === 0 || unsorted.length === 1) {
return unsorted;
}
if (unsorted.length === 2) {
return (unsorted[0] <= unsorted[1]) ? unsorted
: unsorted.reverse();
}
var pivot_index = getRandomInt(0, unsorted.length);
var pivot = unsorted[pivot_index];
var left = [], mid = [], right = [];
for(var i=0;i<unsorted.length;i++) {
if (unsorted[i] < pivot) {
left.push(unsorted[i]);
} else if (unsorted[i] == pivot) {
mid.push(unsorted[i]);
} else {
right.push(unsorted[i]);
}
}
return quick_sort(left)
.concat(mid)
.concat(quick_sort(right));
};
var sorted = quick_sort(array);
console.log(sorted);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment