Three-Way Quick Sort for Duplicate Keys
Sort arrays in place with a three-way partition that groups equal keys, avoiding quadratic behavior when many duplicate values are present.
Code
export function quickSort(items, compare = defaultCompare) {
if (!Array.isArray(items)) throw new TypeError("items must be an array");
if (typeof compare !== "function") throw new TypeError("compare must be a function");
sortRange(items, 0, items.length - 1, compare);
return items;
}
function sortRange(items, low, high, compare) {
while (low < high) {
const pivot = items[low + ((high - low) >>> 1)];
let less = low;
let index = low;
let greater = high;
while (index <= greater) {
const order = compare(items[index], pivot);
if (order < 0) {
swap(items, less, index);
less += 1;
index += 1;
} else if (order > 0) {
swap(items, index, greater);
greater -= 1;
} else {
index += 1;
}
}
if (less - low < high - greater) {
sortRange(items, low, less - 1, compare);
low = greater + 1;
} else {
sortRange(items, greater + 1, high, compare);
high = less - 1;
}
}
}
function swap(items, left, right) {
const temporary = items[left];
items[left] = items[right];
items[right] = temporary;
}
function defaultCompare(left, right) {
return left < right ? -1 : left > right ? 1 : 0;
}
const words = ["delta", "alpha", "charlie", "alpha", "bravo", "alpha"];
console.log(quickSort([...words]));
console.log(quickSort([...words], (left, right) => right.localeCompare(left)));Report a problem with this exampleOpens a pre-filled issue on GitHub.