Heapsort

Also known as: heap sort

On this page 7

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.

StepWhat happensCost
Build heapSift down every internal node, bottom to topO(n) with Floyd’s method
Extract maximumSwap the root with the last heap elementO(1) per step
Sift downMove the new root down to its correct levelO(log n) per step
RepeatShrink the heap until one element remainsn – 1 iterations
TotalBuild plus all extractionsO(n log n)
Phases of heapsort and their cost

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.

PropertyValuePractical consequence
Worst-case timeO(n log n)No adversarial slowdown
Auxiliary spaceO(1)Suitable for tight memory budgets
StabilityNot stableEqual keys may change order
AdaptivityNot adaptiveSorted input gives little speedup
ComparisonsAbout 2n log2 n in the worst caseMore than merge sort needs
Cache behaviorPoor locality on large arraysSlower than quicksort in practice
Main properties of heapsort

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.

AlgorithmWorst-case timeExtra memoryStable
HeapsortO(n log n)O(1)No
QuicksortO(n²)O(log n) stackNo
Merge sortO(n log n)O(n) for arraysYes
Insertion sortO(n²)O(1)Yes
IntrosortO(n log n)O(log n) stackNo
Heapsort and related comparison sorts

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.

SituationRecommended choiceReason
Hard real-time deadlineHeapsortBounded worst case, no allocation
Need only the top k itemsPartial heapsort or heap selectionO(n + k log n) instead of full sort
Equal keys must keep orderMerge sort or TimsortHeapsort is not stable
General-purpose library sortIntrosortQuicksort speed with heapsort safety
Nearly sorted dataInsertion sort or TimsortAdaptive algorithms exploit order
When heapsort is the right tool

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.