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 per round. Heap sort keeps the values in a heap, so the maximum is always at index 0 and restoring the heap costs only .
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.
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 aLeft 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].
- 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.
- 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. - Repeat step 2 until one value is left.
Complexity
| Case | Input | Comparisons | Time |
|---|---|---|---|
| Best | all keys equal | ||
| Average | random | ||
| Worst | sorted ascending |
Building the heap costs . Most parents are near the bottom, so most sift-downs are short. Each of the extractions sinks a value by up to levels with two comparisons per level.
The best case needs equal keys: no value sinks, and each sift-down stops after one check. With distinct keys, every input needs about comparisons or more [2].
Implementations
- Standard: bottom-up construction in , 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 - 1downwards. 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
- T. H. Cormen et al., Introduction to Algorithms, 3rd ed., MIT Press, 2009.
- 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.