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)));Output
Captured from a sandboxed run of this snippet in the build pipeline.
[ 'alpha', 'alpha', 'alpha', 'bravo', 'charlie', 'delta' ]
[ 'delta', 'charlie', 'bravo', 'alpha', 'alpha', 'alpha' ]What the code does
Count the functions quickSort, sortRange, swap and defaultCompare as the entire surface area of Three-Way Quick Sort for Duplicate Keys.
Two loops stack here: while (low < high) selects, while (index <= greater) processes. Failure is loud: TypeError aborts the current operation instead of degrading it.
Points of care
- The guard
typeof compare !== "function"short-circuits the flow with an earlythrowwhen its condition holds.
Applying it
The main signature reads export function quickSort(items, compare = defaultCompare)
quickSort is the public entry point; everything else in the file exists to support it.
Statements that matter
if (typeof compare !== "function") throw new TypeError("compare must be a function");
if (!Array.isArray(items)) throw new TypeError("items must be an array");
return left < right ? -1 : left > right ? 1 : 0;
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.Duplicate Line RemoverFind unique, duplicate, or counted lines with optional case sensitivity and whitespace trimming, all processed locally in the browser.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.
FAQ
- How does the snippet fail?
- The code throws `TypeError` — the guard `typeof compare !== "function"` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `quickSort`, `sortRange`, `swap` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.