/utils

Heap Sort

Build a max-heap inside the array, then repeatedly swap the maximum behind the heap. O(n log n) in the worst case with O(1) extra space.

SolvesSorting

best
O(n)
average
O(n log n)
worst
O(n log n)
space
O(1)

Selection sort finds the maximum by scanning, which costs O(n)O(n) per round. Heap sort keeps the values in a heap, so the maximum is always at index 0 and restoring the heap costs only O(log⁡n)O(\log n).

All keys equal: every sift-down stops after one check, so no value sinks. That is about 3n comparisons: O(n). With distinct keys the best case is about n log₂ n comparisons.

50515253root54555657child
1def sift_down(a, root, size):2    while 2 * root + 1 < size:3        child = 2 * root + 14        if child + 1 < size:5            if a[child] < a[child + 1]:6                child = child + 17        if a[root] >= a[child]:8            break9        a[root], a[child] = a[child], a[root]10        root = child11 12 13def heap_sort(a):14    n = len(a)15    # build a max-heap, last parent first16    for start in range(n // 2 - 1, -1, -1):17        sift_down(a, start, n)18    # move the maximum behind the heap19    for end in range(n - 1, 0, -1):20        a[0], a[end] = a[end], a[0]21        sift_down(a, 0, end)22    return a
1 / 57

Left child of index 3 is index 7.

comparisons
0
swaps
0

How it works

The array is read as a binary tree. The children of index i are 2i + 1 and 2i + 2. In a max-heap every parent is at least as large as its children [1].

  1. Build. For each parent from the last one down to index 0, sift it down: swap it with its larger child until it is not smaller than both children.
  2. Extract. Swap the maximum a[0] with the last heap value. The heap is one shorter and the maximum is final. Sift the new root down to restore the heap.
  3. Repeat step 2 until one value is left.

Complexity

CaseInputComparisonsTime
Bestall keys equal≈3n\approx 3nO(n)O(n)
Averagerandom≈2nlog⁡2n\approx 2n \log_2 nO(nlog⁡n)O(n \log n)
Worstsorted ascending≈2nlog⁡2n\approx 2n \log_2 nO(nlog⁡n)O(n \log n)

Building the heap costs O(n)O(n). Most parents are near the bottom, so most sift-downs are short. Each of the n−1n - 1 extractions sinks a value by up to log⁡2n\log_2 n levels with two comparisons per level.

The O(n)O(n) best case needs equal keys: no value sinks, and each sift-down stops after one check. With distinct keys, every input needs about nlog⁡2nn \log_2 n comparisons or more [2].

Implementations

  • Standard: bottom-up construction in O(n)O(n), then extraction. The heap lives in the front of the array and the sorted part grows from the back.

Pitfalls

  • Build the heap from the last parent n // 2 - 1 downwards. Starting at the root does not produce a heap.
  • A sift-down must stop at the heap size, not at len(a). Otherwise it pulls sorted values back in.

Related

References

  1. T. H. Cormen et al., Introduction to Algorithms, 3rd ed., MIT Press, 2009.
  2. R. Schaffer and R. Sedgewick, “The Analysis of Heapsort,” Journal of Algorithms, vol. 15, no. 1, pp. 76–100, 1993.

Further reading

  • D. E. Knuth, The Art of Computer Programming, Volume 3: Sorting and Searching, 2nd ed., Addison-Wesley, 1998.
  • K. Mehlhorn and P. Sanders, Algorithms and Data Structures: The Basic Toolbox, Springer, 2008.

Full bibliography