Heapsort, also written heap sort, is a comparison-based sorting algorithm that arranges an array into a binary heap and then repeatedly moves the largest remaining element to the end of the array. Among classic algorithms in programming, it is valued for combining a guaranteed O(n log n) running time with in-place operation that needs only O(1) extra memory.
The method was published by J. W. J. Williams in 1964, and Robert W. Floyd soon improved the heap-construction phase to run in linear time. Heapsort is not stable and usually runs slower than a well-tuned quicksort on modern hardware, yet it remains a standard building block, most visibly as the worst-case safeguard inside introsort.
How heapsort orders an array
Heapsort works in two phases. First it rearranges the input into a max-heap, a complete binary tree stored in the array itself in which every parent is greater than or equal to its children. Then it repeatedly swaps the root with the last element of the heap, shrinks the heap by one and restores the heap property.
The tree needs no pointers. For a zero-based array, the children of the element at index i sit at indices 2i + 1 and 2i + 2, and its parent sits at index (i – 1) / 2 rounded down. This implicit layout is what makes heapsort an in-place algorithm.
The table below shows the steps of the algorithm and the cost each one contributes for an array of n elements.
| Step | What happens | Cost |
|---|---|---|
| Build heap | Sift down every internal node, bottom to top | O(n) with Floyd’s method |
| Extract maximum | Swap the root with the last heap element | O(1) per step |
| Sift down | Move the new root down to its correct level | O(log n) per step |
| Repeat | Shrink the heap until one element remains | n – 1 iterations |
| Total | Build plus all extractions | O(n log n) |
The key operation is sift-down: compare a node with its larger child and swap them if the child is bigger, continuing until the node is no smaller than its children or reaches a leaf. Because a complete tree of n nodes has a height of about log2 n, each sift-down needs at most that many levels of comparisons.
Complexity and key properties of heapsort
Heapsort has the same O(n log n) bound in the best, average and worst case, which makes its running time highly predictable. The building phase is linear because most nodes sit near the bottom of the tree and move only a few levels, so the extraction phase dominates the total cost.
The following table summarizes the properties that matter when engineers compare heapsort with other sorting algorithms.
| Property | Value | Practical consequence |
|---|---|---|
| Worst-case time | O(n log n) | No adversarial slowdown |
| Auxiliary space | O(1) | Suitable for tight memory budgets |
| Stability | Not stable | Equal keys may change order |
| Adaptivity | Not adaptive | Sorted input gives little speedup |
| Comparisons | About 2n log2 n in the worst case | More than merge sort needs |
| Cache behavior | Poor locality on large arrays | Slower than quicksort in practice |
The lack of locality is the main practical drawback. Sift-down jumps from index i to roughly 2i, so on large arrays nearly every level touches a different cache line. Variants such as bottom-up heapsort reduce the number of comparisons to close to n log2 n, and d-ary heaps with four or more children per node shorten the tree and improve cache use.
Heapsort compared with quicksort and merge sort
Heapsort sits between its two best-known rivals: it shares the worst-case guarantee of merge sort and the in-place memory profile of quicksort, but it does not match either one on raw average speed or stability.
| Algorithm | Worst-case time | Extra memory | Stable |
|---|---|---|---|
| Heapsort | O(n log n) | O(1) | No |
| Quicksort | O(n²) | O(log n) stack | No |
| Merge sort | O(n log n) | O(n) for arrays | Yes |
| Insertion sort | O(n²) | O(1) | Yes |
| Introsort | O(n log n) | O(log n) stack | No |
Introsort shows how these strengths combine. It starts with quicksort, switches to heapsort when the recursion depth exceeds about 2 log2 n, and finishes small partitions with insertion sort. Many standard library sort routines for unstable sorting follow this design, so heapsort often runs only as a fallback rather than as the primary algorithm.
Choosing heapsort in practice
Heapsort is a good choice when predictable timing and constant memory matter more than average speed. These conditions are common in embedded systems, real-time software and kernels, where an unexpected quadratic case or a large temporary buffer is unacceptable.
The decision table below lists typical situations and the sorting approach that usually fits each one best.
| Situation | Recommended choice | Reason |
|---|---|---|
| Hard real-time deadline | Heapsort | Bounded worst case, no allocation |
| Need only the top k items | Partial heapsort or heap selection | O(n + k log n) instead of full sort |
| Equal keys must keep order | Merge sort or Timsort | Heapsort is not stable |
| General-purpose library sort | Introsort | Quicksort speed with heapsort safety |
| Nearly sorted data | Insertion sort or Timsort | Adaptive algorithms exploit order |
The same heap structure also powers the priority queue, which explains why heapsort ideas appear in scheduling, event simulation and graph algorithms such as Dijkstra’s algorithm. Understanding heapsort therefore teaches the heap data structure as much as it teaches sorting.
Common mistakes when implementing heapsort
Most heapsort bugs come from index arithmetic and heap boundaries, because the heap shrinks while the sorted region grows inside the same array.
- Mixing one-based and zero-based formulas, such as using children at 2i and 2i + 1 in a zero-based array.
- Sifting past the current heap size, which pulls already sorted elements back into the heap.
- Building the heap top-down with sift-up, which costs O(n log n) instead of the linear Floyd method.
- Writing sift-down recursively in constrained environments, which adds stack usage and loses the O(1) space benefit.
- Expecting stable output when records with equal keys must preserve their original order.
A reliable test suite checks empty arrays, single elements, duplicates, already sorted input and reverse-sorted input, and compares the output with a trusted library sort on many random arrays.
A non-technical view
Heapsort sorts a list by first arranging it into a tournament-style pyramid. In this pyramid, every item is larger than the items directly below it. The biggest item always sits at the top.
The method then takes the top item and puts it at the end of the list. It repairs the pyramid so the next biggest item rises to the top. It repeats this until the pyramid is empty. The result is a fully sorted list. The main appeal is reliability: heapsort never has a bad day, and it needs almost no extra space to work.
A concrete example
A firmware team builds a controller for an industrial packaging line. Every 50 milliseconds, the controller must sort about 2,000 sensor readings by priority before deciding which actuator to service first. The device has only a few kilobytes of free memory and no dynamic allocation.
Quicksort was rejected because a rare input pattern could push it into quadratic time and miss the deadline. Merge sort needed a second buffer the device could not spare. The team implemented an iterative heapsort working directly on the reading array, using a loop-based sift-down and no recursion.
Timing tests across millions of cycles showed a stable worst case of under 2 ms per sort, well inside the 50 ms budget. The result met the safety review requirement that every control cycle has a provable upper time bound, which was the deciding factor in choosing heapsort.