Heapsort Build And Extract Max Typed
Sort a typed array by building a max heap in place then repeatedly extracting the maximum to the end.
Code
function heapsort(arr: number[]): number[] {
const n = arr.length;
function siftDown(start: number, end: number): void {
let root = start;
while (root * 2 + 1 <= end) {
let child = root * 2 + 1;
if (child + 1 <= end && arr[child] < arr[child + 1]) child++;
if (arr[root] < arr[child]) { [arr[root], arr[child]] = [arr[child], arr[root]]; root = child; } else return;
}
}
for (let i = (n - 2) >>> 1; i >= 0; i--) siftDown(i, n - 1);
for (let end = n - 1; end > 0; end--) { [arr[0], arr[end]] = [arr[end], arr[0]]; siftDown(0, end - 1); }
return arr;
}How the snippet works
Heapsort Build And Extract Max Typed reduces to the functions i, heapsort and siftDown.
Iteration is nested: while (root * 2 + 1 <= end) frames the pass, for (let i = (n - 2) >>> 1; i >= 0; i--) siftDown(i, n - 1); does the per-item step.
Applying it
The main signature reads let i = (n - 2)
Statements that matter
if (arr[root] < arr[child]) { [arr[root], arr[child]] = [arr[child], arr[root]]; root = child; } else return;
for (let end = n - 1; end > 0; end--) { [arr[0], arr[end]] = [arr[end], arr[0]]; siftDown(0, end - 1); }
if (child + 1 <= end && arr[child] < arr[child + 1]) child++;
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. The file defines `i`, `heapsort`, `siftDown` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.