Heapsort

Matt George

Fractional CTO · Founder of Injuria.ai

•20 min read•

Heapsort is a deterministic, comparison-based sorting algorithm[1] that divides its input into a sorted and an unsorted region, iteratively shrinking the unsorted region by extracting the largest element and moving it to the sorted region. It achieves this by maintaining the unsorted region in a binary heap[2] data structure, which allows the algorithm to find the maximum element in constant time and restore the heap properties in logarithmic time.[31] As an in-place algorithm[3], it requires only a constant amount of additional memory, making it highly efficient in environments with strict memory constraints.[32]

Invented in 1964 by J. W. J. Williams and refined shortly after by Robert W. Floyd, heapsort solved a major theoretical problem in computer science by providing a sorting method that guarantees a worst-case time complexity of O(n log n) without requiring the proportional auxiliary storage demanded by mergesort[4]. By mapping a complete binary tree directly onto a flat array, the algorithm avoids the overhead of storing memory pointers, utilizing index arithmetic to traverse between parent and child nodes.

While heapsort is mathematically optimal in its worst-case time and space complexity bounds, it is frequently outperformed in general-purpose software by well-implemented variations of quicksort[5] or mergesort. This performance gap is primarily due to heapsort's memory access patterns, which jump non-sequentially across the array and frequently cause cache misses on modern processor architectures. Because it is immune to the quadratic worst-case degradation of quicksort and the memory allocation failures possible with mergesort, heapsort remains a standard fallback mechanism in language libraries and a primary sorting utility in operating system kernels and embedded systems.

Definition and Problem Statement

The fundamental objective of a sorting algorithm is to arrange a collection of elements into a monotonically increasing or decreasing sequence. In computer science, sorting algorithms are evaluated based on their time complexity[6], which measures the number of computational operations required as a function of the input size, and their space complexity[7], which measures the amount of auxiliary memory required.

Heapsort specifically addresses the challenge of in-place sorting. An in-place algorithm transforms the input using no auxiliary data structures, requiring only a small, constant amount of extra storage space, denoted as O(1) in Big-O notation[8]. Prior to the invention of heapsort, achieving a guaranteed worst-case time complexity of O(n log n) required algorithms like mergesort, which necessitates O(n) auxiliary memory to hold the merged subarrays. Conversely, quicksort operates in-place and is highly efficient on average, but it carries the risk of degrading to O(n^2) time complexity on pathological inputs. Heapsort[9] provides the mathematical guarantee of O(n log n) time and O(1) space simultaneously.

To achieve these bounds, heapsort relies on the binary heap data structure. A binary heap is a complete binary tree[10], meaning every level of the tree is fully populated except possibly the last level, which is filled from left to right. In the context of heapsort, the algorithm typically employs a max-heap, which enforces the heap property: the value of any given node must be greater than or equal to the values of its children.[33] This structural invariant guarantees that the maximum element in the tree is always located at the root node.

A defining characteristic of the binary heap is that it does not require a node-based memory representation with explicit pointers. Instead, the complete binary tree is mapped directly onto a standard, contiguous array data structure[11]. For a zero-indexed array, the root of the tree is placed at index 0. For any node located at index i, its left child is located at index 2i + 1, and its right child is located at index 2i + 2. The parent of any node at index i can be found at index floor((i - 1) / 2). In older literature utilizing one-indexed arrays, the math is even simpler: the left child is at 2i, the right child is at 2i + 1, and the parent is at floor(i / 2). This implicit representation allows the algorithm to traverse the tree structure using basic arithmetic, entirely eliminating the memory overhead and allocation time associated with pointer-based trees.

Mechanism and Implementation

The heapsort algorithm operates in two distinct phases: heap construction and element extraction.

In the first phase, the algorithm transforms the unsorted input array into a valid max-heap. This process, often called build_heap, operates bottom-up. Because the array represents a complete binary tree, all elements located in the second half of the array (from index floor(n / 2) to n - 1) are leaf nodes. By definition, a single node with no children already satisfies the heap property. The algorithm begins at the last non-leaf node, located at index floor(n / 2) - 1, and iterates backward to the root at index 0. For each node, it applies a procedure called sift_down (or heapify).

The sift_down operation is the core mechanical component of heapsort. It takes a node that may violate the heap property and allows it to sink down the tree until the property is restored. The procedure compares the target node with its left and right children. If the node is smaller than either child, it is swapped with the largest of the two children. This swap may cause the node to violate the heap property in its new position, so the procedure repeats iteratively down the affected branch until the node is larger than both of its children or it reaches a leaf position.

Once the build_heap phase is complete, the array is a valid max-heap, and the largest element is guaranteed to be at index 0.

The second phase is the sorting or extraction phase. The algorithm swaps the maximum element at the root (index 0) with the last element in the heap (index n - 1). The maximum element is now in its final, correct position in the sorted array. The algorithm then logically reduces the size of the heap by one, effectively ignoring the newly sorted element at the end of the array. Because the new root element (formerly the last element) likely violates the max-heap property, the algorithm calls sift_down on the root to restore the heap. This process of swapping the root with the last element of the active heap, decrementing the heap size, and sifting down the new root is repeated until the active heap size is reduced to one. At this point, the entire array is sorted.

To illustrate this mechanism, consider the unsorted array [4, 10, 3, 5, 1] with a length of 5.
During the heap construction phase, the last non-leaf node is at index floor(5 / 2) - 1 = 1, which holds the value 10. Its children are 5 and 1. Because 10 is greater than both children, the heap property is satisfied. The algorithm moves to index 0, which holds the value 4. Its children are 10 and 3. The largest child is 10. The algorithm swaps 4 and 10, resulting in the array [10, 4, 3, 5, 1]. The node with value 4 is now at index 1. Its children are 5 and 1. The largest child is 5. The algorithm swaps 4 and 5, resulting in [10, 5, 3, 4, 1]. The node with value 4 is now a leaf, and the max-heap is complete.

During the extraction phase, the algorithm swaps the root (10) with the last element (1), resulting in [1, 5, 3, 4, 10]. The active heap size is reduced to 4. The new root (1) is sifted down. It is swapped with its largest child (5), resulting in [5, 1, 3, 4, 10]. It is then swapped with its next largest child (4), resulting in [5, 4, 3, 1, 10]. The heap is restored. Next, the root (5) is swapped with the last active element (1), yielding [1, 4, 3, 5, 10]. The heap size is reduced to 3. The root (1) is sifted down and swapped with 4, yielding [4, 1, 3, 5, 10]. The root (4) is swapped with the last active element (3), yielding [3, 1, 4, 5, 10]. The heap size is reduced to 2. The root (3) is sifted down, but it is already larger than its child (1). Finally, the root (3) is swapped with the last active element (1), yielding [1, 3, 4, 5, 10]. The heap size is reduced to 1, and the array is fully sorted.

function heapsort(array)
    n = length(array)
    
    // Phase 1: Build the max-heap
    for i from floor(n / 2) - 1 down to 0
        siftDown(array, i, n)
        
    // Phase 2: Extract elements one by one
    for i from n - 1 down to 1
        swap(array[0], array[i])
        siftDown(array, 0, i)

function siftDown(array, i, max_size)
    while (2 * i + 1) < max_size
        left = 2 * i + 1
        right = 2 * i + 2
        largest = i
        
        if array[left] > array[largest]
            largest = left
        if right < max_size and array[right] > array[largest]
            largest = right
            
        if largest == i
            return // The heap property is satisfied
            
        swap(array[i], array[largest])
        i = largest // Continue sifting down

Computational Complexity

The mathematical analysis of heapsort demonstrates its strict performance guarantees. The time complexity of the algorithm is the sum of the time required for the heap construction phase and the extraction phase.

The build_heap phase requires O(n) time. While a naive analysis might suggest that calling sift_down (which takes O(log n) time) for n/2 nodes would result in O(n log n) time, a tighter mathematical bound applies. The time required for sift_down is proportional to the height of the node in the tree. In a complete binary tree of n elements, the height of the tree is floor(log2(n)). The number of nodes at any given height h is at most ceiling(n / 2^(h+1)). The total work is the sum over all heights h of the number of nodes at height h multiplied by the cost to sift down from that height, which is proportional to h. This summation, Sum(h * n / 2^(h+1)) from h=0 to log2(n), forms a geometric series that converges to a linear bound. By factoring out n/2, the series becomes (n/2) * Sum(h / 2^h). The infinite series Sum(h / 2^h) evaluates exactly to 2. Multiplying this result by n/2 yields n, proving that a binary heap can be constructed in strictly O(n) operations.

The extraction phase requires O(n log n) time. The algorithm performs n - 1 extractions. In each step, the root is swapped with a leaf, and the new root must be sifted down. In the worst case, the new root must travel all the way back down to the bottom level of the tree, requiring a number of comparisons proportional to the height of the tree, which is log2(n). At each level, two comparisons are made: one to find the larger child, and one to compare the parent to that child. Therefore, the standard extraction phase requires approximately 2n log2(n) comparisons. This phase dominates the overall running time, resulting in a worst-case, average-case, and best-case time complexity of O(n log n).

Regarding space complexity, heapsort is strictly an in-place algorithm. It requires only a few variables to track array indices and sizes, resulting in an auxiliary space complexity of O(1). Unlike recursive implementations of quicksort or mergesort, an iterative implementation of heapsort does not consume call stack memory, making its memory footprint entirely predictable.

Heapsort is not a stable sort. Stability in sorting algorithms means that two elements with equal keys appear in the same order in the sorted output as they did in the unsorted input. During the build_heap phase, and particularly during the long-distance swaps of the extraction phase, the relative ordering of duplicate elements is frequently inverted.

Discovery and History

The heapsort algorithm was invented by J. W. J. Williams, a British computer scientist, who published it in 1964 in the Communications of the ACM under the title "Algorithm 232: Heapsort"[12]. Williams originally developed the binary heap data structure to implement an efficient priority queue[13], a system where the highest-priority element can be continuously extracted. He recognized that by inserting all elements of an array into this priority queue and then sequentially extracting them, the result would be a sorted array.

In Williams' original formulation, the heap was constructed by inserting elements one at a time into an initially empty heap. Because each insertion takes O(log n) time, this original construction method required O(n log n) time. Later in 1964, Robert W. Floyd published "Algorithm 245: Treesort 3"[14] in the same journal. Floyd introduced the bottom-up build_heap procedure, which optimized the heap construction phase to run in linear O(n) time. Floyd's refinement established the modern, standard version of the heapsort algorithm.

The context of this discovery was a period of rapid advancement in algorithmic theory. C. A. R. Hoare had published his paper on "Algorithm 64: Quicksort"[15] in 1961, and John von Neumann had developed mergesort in 1945. Early computing environments had severely limited memory, often measured in kilobytes. Mergesort's requirement for a duplicate array of memory was often prohibitive. Quicksort operated in-place but lacked a worst-case guarantee, meaning a poorly shuffled input could cause the program to stall in quadratic time. Heapsort provided a mathematical resolution to this problem, proving that O(n log n) in-place sorting was possible.

Subsequent decades saw deep mathematical analysis of the algorithm. In 1987, Svante Carlsson published "Average-case results on heapsort"[16] in BIT Numerical Mathematics, providing a rigorous proof of the algorithm's average-case behavior and demonstrating that it requires slightly fewer comparisons on average than in the worst case, though still bounded by O(n log n).[34] Donald E. Knuth extensively documented the algorithm and its variations in his seminal work, "The Art of Computer Programming"[17], cementing its status as a foundational algorithm in computer science.

Important Variants

Several variations of heapsort have been developed to optimize its comparison count or adapt it to specific data patterns.

Bottom-Up Heapsort: Introduced by Robert W. Floyd (Ingo Wegener analyzed it in 1993) in his paper "BOTTOM-UP-HEAPSORT, a new variant of HEAPSORT beating, on an average, QUICKSORT"[18], this variant reduces the number of comparisons required during the extraction phase. In standard heapsort, the sift_down operation requires two comparisons per level: one to find the larger of the two children, and one to determine if the parent is smaller than the largest child. Wegener noted that during the extraction phase, the element placed at the root is a former leaf node, meaning it is almost certainly smaller than most nodes in the tree and will likely sift down to the bottom. Bottom-up heapsort skips the comparison with the parent on the way down, simply tracing the path of maximum children all the way to a leaf level. It then searches upward from that leaf to find the correct insertion point. This reduces the number of comparisons per extraction from 2 log2(n) to approximately 1 log2(n), making it competitive with quicksort in terms of total comparisons.

Introsort (Introspective Sort): Invented by David R. Musser in 1997 and detailed in "Introspective Sorting and Selection Algorithms"[19], introsort[20] is a hybrid algorithm that combines the practical speed of quicksort with the worst-case guarantees of heapsort. The algorithm begins by running quicksort. It tracks the recursion depth as it partitions the array. If the recursion depth exceeds a predetermined limit (typically 2 * log2(n)), it indicates that quicksort is encountering a pathological input and degrading toward quadratic time. At this threshold, introsort halts the quicksort partitioning and switches to heapsort for the remaining unsorted subarrays.

Smoothsort: Developed by Edsger W. Dijkstra in 1981 and published as "Smoothsort, an alternative for sorting in situ"[21], smoothsort[22] is a highly complex variation designed to achieve O(n) time complexity on arrays that are already partially sorted. Instead of a single binary heap, smoothsort maintains a forest of heaps whose sizes are dictated by the Leonardo numbers. As elements are processed, heaps are merged or split according to strict mathematical rules. While it maintains the O(n log n) worst-case bound and operates in-place, the overhead of managing the Leonardo heaps makes it slower than standard heapsort on random data, and its implementation complexity has limited its practical adoption.

Weak-Heap Sort: Introduced by Ronald Dutton in 1993 and published as "Weak-Heap Sort"[23], this variant relaxes the standard heap property.[35] In a weak heap, the root node has no left child, and every other node is only required to be larger than the nodes in its right subtree. This structural relaxation reduces the number of comparisons required to sort n elements to n log2(n) + 0.087n (the n log2(n) - 0.9n bound is for a later refinement), which approaches the theoretical information-theoretic lower bound for comparison sorting. However, a weak heap requires an extra array of bits to track the tree structure, meaning it consumes O(n) auxiliary space and is not strictly an in-place algorithm.

Ternary and d-ary Heapsort: Based on the d-ary heap[24] generalized by Donald B. Johnson in 1975, ternary heapsort uses a tree structure where each node has three children instead of two. For a zero-indexed array, the children of a node at index i are located at 3i + 1, 3i + 2, and 3i + 3. A ternary heap reduces the overall height of the tree to log3(n). During the sift_down operation, the algorithm must find the largest of three children, requiring two comparisons, and then compare that maximum child to the parent, requiring a third comparison. While it requires more comparisons per level than a binary heap, the reduced tree height results in fewer swap operations and slightly better memory cache behavior.

Pattern-Defeating Quicksort (pdqsort): Developed by Orson Peters in 2015 and detailed in "Pattern-defeating Quicksort"[25], pdqsort is a modern successor to introsort. While introsort blindly switches to heapsort when quicksort recursion goes too deep, pdqsort actively analyzes the input array for existing patterns. It uses heapsort as a strict fallback mechanism to guarantee O(n log n) worst-case performance, but it incorporates advanced partitioning strategies to achieve O(n) time complexity on arrays that are already sorted or strictly reverse-sorted.

Real-World Applications

While rarely used as the default sorting algorithm in high-level programming languages, heapsort is heavily utilized in systems programming, embedded environments, and specific library implementations where predictability is required.

Operating System Kernels: The Linux kernel utilizes heapsort for its generic sorting utility, located in the source tree at lib/sort.c[26]. In kernel space, memory allocation via functions like kmalloc can fail under heavy load, making mergesort unsafe. The kernel stack is strictly limited in size (often just 4 to 8 kilobytes), meaning the deep recursion possible in quicksort could cause a stack overflow and a subsequent kernel panic. Heapsort is chosen because an iterative implementation requires zero dynamic memory allocation and zero stack frames, guaranteeing safe execution under all system conditions.

Embedded Systems and Safety-Critical Software: In the domain of embedded systems, predictability is prioritized over average-case speed. Standards such as the Motor Industry Software Reliability Association guidelines, commonly known as MISRA C[27], impose strict constraints on software development for automotive and aerospace applications. These guidelines frequently prohibit the use of dynamic memory allocation and recursive function calls to ensure deterministic execution. Heapsort satisfies all safety constraints, making it the standard sorting algorithm for flight control systems, medical devices, and engine control units.

Standard Libraries: Heapsort is the standard fallback mechanism in many language libraries via the introsort and pdqsort algorithms. The C++ Standard Template Library specification requires std::sort to have an O(n log n) worst-case complexity. Most modern C++ compilers implement std::sort[28] using introsort, relying on heapsort to rescue the algorithm if quicksort partition trees become unbalanced. The .NET framework's Array.Sort and the Rust standard library's unstable sort also utilize heapsort as a fallback mechanism.

Priority Queues: The binary heap structure underlying heapsort is the standard implementation for priority queues across almost all programming languages. For example, Java's java.util.PriorityQueue, Python's heapq module, and C++'s std::priority_queue all use the exact array-mapped tree structure and sift_down mechanics defined by Williams and Floyd. In these applications, the full array is not sorted at once; instead, elements are inserted and extracted dynamically, utilizing the O(log n) bounds of the heap operations.

Significance and Tradeoffs

Heapsort holds a specific place in algorithmic theory as the standard proof that O(n log n) time and O(1) space can be achieved simultaneously. Its practical application is defined by a distinct set of tradeoffs compared to other optimal sorting algorithms.

The primary disadvantage of heapsort is its poor cache locality. Modern CPU architectures rely heavily on memory caches (L1, L2, and L3) to bridge the speed gap between the processor and main memory. When a processor reads a value from memory, it fetches an entire cache line (typically 64 bytes) containing adjacent data. Algorithms like quicksort and mergesort access memory sequentially. This sequential access pattern allows hardware prefetchers to anticipate future memory requests and load the next cache lines into the L1 or L2 cache before the processor explicitly requests them. Heapsort accesses memory non-sequentially. During the sift_down operation, a node at index i is compared with its children at 2i + 1 and 2i + 2. As the heap grows larger than the CPU cache, these indices map to entirely different memory pages. Every step down the tree effectively guarantees a cache miss, forcing the CPU to stall and wait for a slow main memory fetch. Consequently, despite having the same asymptotic time complexity, heapsort is typically two to three times slower than quicksort on large, randomly ordered arrays.

Heapsort is not adaptive. Algorithms like Timsort[29] (the default in Python and Java) or smoothsort can detect existing order in the input data, reducing their running time to O(n) for nearly sorted arrays. Heapsort is entirely blind to existing order; the build_heap phase will aggressively break apart pre-sorted sequences to enforce the max-heap property, and the extraction phase will still require O(n log n) operations to reassemble them.

Despite these drawbacks, heapsort's significance remains intact due to its security profile. Algorithmic complexity attacks occur when a malicious actor supplies specifically crafted input data designed to trigger the worst-case performance of an algorithm, causing a denial-of-service condition. Quicksort is highly vulnerable to this type of attack. If a server uses a naive quicksort implementation to process user-supplied data, an attacker can submit an array that forces the algorithm to degrade to O(n^2) time complexity, consuming excessive CPU cycles and rendering the server unresponsive. Heapsort provides an absolute mathematical ceiling on both execution time and memory consumption. Because its worst-case time complexity is strictly bounded to O(n log n) regardless of the input distribution, it is completely immune to algorithmic complexity attacks. By providing a level of deterministic safety that is required in cryptography, aerospace software, and core operating system routines, heapsort remains a fundamental building block of computer science education and systems engineering, as documented in reference texts like "Introduction to Algorithms"[30] by Cormen, Leiserson, Rivest, and Stein.[32]

Sources (35)
  1. Wikipedia: sorting algorithm
  2. Wikipedia: binary heap
  3. Wikipedia: in-place algorithm
  4. Wikipedia: mergesort
  5. Wikipedia: quicksort
  6. Wikipedia: time complexity
  7. Wikipedia: space complexity
  8. Big-O notation
  9. Heapsort
  10. Wikipedia: binary tree
  11. Wikipedia: array data structure
  12. ACM Digital Library
  13. Wikipedia: priority queue
  14. ACM Digital Library
  15. ACM Digital Library
  16. "Average-case results on heapsort"
  17. www-cs-faculty.stanford.edu: "The Art of Computer Programming"
  18. "BOTTOM-UP-HEAPSORT, a new variant of HEAPSORT beating, on an average, QUICKSORT"
  19. "Introspective Sorting and Selection Algorithms"
  20. Wikipedia: introsort
  21. "Smoothsort, an alternative for sorting in situ"
  22. Wikipedia: smoothsort
  23. "Weak-Heap Sort"
  24. Wikipedia: d-ary heap
  25. "Pattern-defeating Quicksort"
  26. `lib/sort.c`
  27. MISRA C
  28. `std::sort`
  29. Wikipedia: Timsort
  30. mitpress.mit.edu: "Introduction to Algorithms"
  31. Peter Gloor, Elements of Hypermedia Design: Techniques for Navigation & Visualization in Cyberspace (Springer Science & Business Media, 2013)
  32. Thomas H Cormen, Charles E Leiserson, Ronald L Rivest, Introduction To Algorithms (MIT Press, 2001)
  33. Stephan Diehl, Software Visualization (Springer Science & Business Media, 2007)
  34. Michel Schellekens, A Modular Calculus for the Average Cost of Data Structuring (Springer Science & Business Media, 2008)
  35. Stefan Näher, Dorothea Wagner, Algorithm Engineering (Springer Science & Business Media, 2007)

Recommended reading