Skip to content

Instantly share code, notes, and snippets.

@kamilogorek
Last active August 29, 2015 14:02
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 kamilogorek/8e4456e6107bf7687e0c to your computer and use it in GitHub Desktop.
Save kamilogorek/8e4456e6107bf7687e0c to your computer and use it in GitHub Desktop.
Quicksort on 1.000.000 random elements within 0 – 1.000.000 range
/**
* Quicksort implementation by Nicholas C. Zakas
* http://www.nczonline.net/blog/2012/11/27/computer-science-in-javascript-quicksort/
*/
var items = [];
for (var i = 0; i < 1000000; i++) {
items.push(Math.round(Math.random() * 1000000));
}
function swap(items, firstIndex, secondIndex){
var temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
}
function partition(items, left, right) {
var pivot = items[Math.floor((right + left) / 2)];
var i = left;
var j = right;
while (i <= j) {
while (items[i] < pivot) {
i++;
}
while (items[j] > pivot) {
j--;
}
if (i <= j) {
swap(items, i, j);
i++;
j--;
}
}
return i;
}
function quickSort(items, left, right) {
var index;
if (items.length > 1) {
left = typeof left != "number" ? 0 : left;
right = typeof right != "number" ? items.length - 1 : right;
index = partition(items, left, right);
if (left < index - 1) {
quickSort(items, left, index - 1);
}
if (index < right) {
quickSort(items, index, right);
}
}
return items;
}
var start = performance.now();
var results = quickSort(items);
console.log('Time:', performance.now() - start);
console.log('Results:', results.slice(-10).reverse())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment