Heapsort
Turn the array into a max-heap, then repeatedly move the largest value to the end: guaranteed O(n log n) with O(1) extra memory, but not stable.
Description
Heapsort uses a binary heap stored in the array itself. First it rearranges the array into a max-heap, where every parent is at least as large as its children, in O(n) time. The largest value is now at index 0.
Then it repeats: swap the root with the last element of the heap, shrink the heap by one (that last position is now final), and sift down the new root to restore the heap property. After n − 1 rounds, the array is sorted.
Heapsort's appeal is its guarantees: O(n log n) in the worst case and O(1) extra memory, a combination neither quicksort (worst case O(n²)) nor merge sort (O(n) memory) offers. Its weaknesses are that it isn't stable and its jumps around the array are unfriendly to CPU caches, so it's usually slower than quicksort in practice. That's why introsort, used by many C++ standard libraries, starts with quicksort and falls back to heapsort only when recursion gets too deep.
How it works
The array as a max-heap: the root is the largest value
- index 0: 41 (root)
- index 1: 37, parent 41
- index 2: 29, parent 41
- index 3: 22, parent 37
- index 4: 13, parent 37
- index 5: 5, parent 29
- index 6: 14, parent 29
- index 7: 10, parent 22
Step through: heapsort
Step 1 of 22Start with 8 values.
Complexity
| Operation | Average | Worst |
|---|---|---|
| Build the heap | O(n) | O(n) |
| Sort (any input) | O(n log n) | O(n log n) |
Space: O(1)
TypeScript implementation
In-place heapsort with a max-heap built bottom-up.
// In-place heapsort: build a max-heap, then repeatedly move the max to the end.
function siftDown(a: number[], root: number, end: number): void {
for (;;) {
let child = 2 * root + 1;
if (child > end) return;
if (child + 1 <= end && a[child + 1] > a[child]) child++; // the larger child
if (a[root] >= a[child]) return;
[a[root], a[child]] = [a[child], a[root]];
root = child;
}
}
export function heapsort(a: number[]): number[] {
const n = a.length;
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) siftDown(a, i, n - 1); // O(n) heap build
for (let end = n - 1; end > 0; end--) {
[a[0], a[end]] = [a[end], a[0]]; // largest to its final place
siftDown(a, 0, end - 1);
}
return a;
}
export function demo(): string[] {
const heap = [29, 10, 14, 37, 13, 5, 41, 22];
for (let i = Math.floor(heap.length / 2) - 1; i >= 0; i--) siftDown(heap, i, heap.length - 1);
return [
`as a max-heap: [${heap.join(", ")}]`,
`sorted: [${heapsort([29, 10, 14, 37, 13, 5, 41, 22]).join(", ")}]`,
];
}When to use it
Use it when
- You need a guaranteed O(n log n) sort with no extra memory: embedded systems, kernels, real-time code.
- As the fallback inside introsort.
- Partial sorting: the k largest values come out after k rounds.
Avoid it when
- You need stability: use merge sort or Timsort.
- Average speed matters most: quicksort is usually faster.
Pitfalls
- Building the heap with n pushes (O(n log n)) instead of sifting down from the middle (O(n)).
- Index errors in child calculations: with zero-based arrays, children are at 2i + 1 and 2i + 2.
- Assuming stability.
Alternatives
Quicksort
Choose it when you want the fastest average-case in-memory sort.
Merge sort
Choose it when you need stability and can spare O(n) memory.
Binary heap
Choose it when you need a priority queue rather than a sorted array.