Skip to content

Instantly share code, notes, and snippets.

@beatak
Created March 29, 2020 14:54
Show Gist options
  • Save beatak/9ea1c92816fc62e32c27cda213701d7e to your computer and use it in GitHub Desktop.
Save beatak/9ea1c92816fc62e32c27cda213701d7e to your computer and use it in GitHub Desktop.
'use strict';
const quickSort = function (items, left, right) {
let index;
if (left === undefined) {
left = 0;
}
if (right === undefined) {
right = items.length - 1;
}
if (items.length > 1) {
index = quickSort.partition(items, left, right); //index returned from partition
if (left < index - 1) { //more elements on the left side of the pivot
quickSort(items, left, index - 1);
}
if (index < right) { //more elements on the right side of the pivot
quickSort(items, index, right);
}
}
return items;
};
quickSort.partition = function (items, left, right) {
const pivot = items[ Math.floor((right + left) / 2) ]; //middle element
let i = left; //left pointer
let j = right; //right pointer
while (i <= j) {
{
while (items[i] < pivot) {
i++;
}
while (items[j] > pivot) {
j--;
}
if (i <= j) {
quickSort.swap(items, i, j); //sawpping two elements
i++;
j--;
}
}
}
return i;
};
quickSort.swap = function (items, leftIndex, rightIndex) {
const temp = items[leftIndex];
items[leftIndex] = items[rightIndex];
items[rightIndex] = temp;
};
// ============================
const checkOrder = function (arr) {
let last = -Infinity;
arr.forEach(each => {
if (each < last) {
throw new Error('wrong!');
}
last = each;
});
};
const measure = function (func) {
const begin = Date.now();
func();
console.log(` Took: ${Date.now() - begin} milsec`);
};
const dupe = function (arr) {
return JSON.parse(JSON.stringify(arr));
}
// ============================
const main = function () {
const arr = [];
for (let i = 0; i < 10000000; ++i) {
arr.push( Math.round( Math.random() * 11 ) );
}
let q = dupe(arr);
let b = dupe(arr);
let prim = dupe(arr);
// console.log(`orig: ${JSON.stringify(arr)}`);
console.log('quick sort');
measure(() => quickSort(q));
console.log('builtin sort');
measure(() => b.sort());
console.log('primitive sort');
measure(() => prim.sort((a, b) => {return (a === b) ? 0 : (a < b ? -1 : 1)}));
// console.log(`orig: ${JSON.stringify(arr)}\nQuick: ${JSON.stringify(q)}\nBuilt-in: ${JSON.stringify(b)}\nPrimitive: ${JSON.stringify(prim)}`);
if (JSON.stringify(q) !== JSON.stringify(b)) {
console.log('builtin result is different');
}
if (JSON.stringify(q) !== JSON.stringify(prim)) {
console.log('primitive result is different');
}
try {
checkOrder(q)
} catch (err) {
console.log('quicksort did not pass');
}
try {
checkOrder(b)
} catch (err) {
console.log('built-in sort did not pass');
}
try {
checkOrder(prim)
} catch (err) {
console.log('primitive sort did not pass');
}
};
// ============================
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment