In-Place Heap Sort With Comparator
Build a max heap and sort an array in place in O(n log n) time with no extra allocations, using a pluggable comparator for custom orders.
Code
export function heapSort(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");
const size = items.length;
for (let root = (size >> 1) - 1; root >= 0; root -= 1) {
siftDown(items, root, size, compare);
}
for (let end = size - 1; end > 0; end -= 1) {
swap(items, 0, end);
siftDown(items, 0, end, compare);
}
return items;
}
function siftDown(items, root, size, compare) {
let current = root;
while (true) {
const left = current * 2 + 1;
const right = left + 1;
let largest = current;
if (left < size && compare(items[left], items[largest]) > 0) largest = left;
if (right < size && compare(items[right], items[largest]) > 0) largest = right;
if (largest === current) return;
swap(items, current, largest);
current = largest;
}
}
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 numbers = [9, 4, 7, 1, 8, 4, 2];
console.log(heapSort(numbers));
console.log(heapSort([3, 1, 2], (left, right) => right - left));How the snippet works
The working surface is the functions root, heapSort, siftDown and swap — everything else is wiring.
Two loops stack here: for (let root = (size >> 1) - 1; root >= 0; root -= 1) selects, for (let end = size - 1; end > 0; end -= 1) processes. TypeError is the guard’s signal — thrown at the branch, before any partial work happens.
What to watch for
- The guard
typeof compare !== "function"short-circuits the flow with an earlythrowwhen its condition holds.
Applying it
The primary signature is export function heapSort(items, compare = defaultCompare)
Treat heapSort as the API: import it, and ignore the supporting code.
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.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.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.
FAQ
- How does the snippet fail?
- It throws `TypeError` before any real work runs, via the guard `typeof compare !== "function"` — handle it at the call site or let it propagate deliberately.
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. The file defines `root`, `heapSort`, `siftDown` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.