Sub topic 17
Heap sort: algorithm and cost
This chapter assumes you can already build a max-heap with sift_down (bottom-up construction) and that you know the array index rules for a 0-based heap: the children of i are 2i+1 and 2i+2, and the parent is (i-1)//2. It also assumes you can read O(n) and O(n log n) bounds. Here you combine those pieces into an in-place sorting algorithm, trace it by hand, and count its cost the way GATE questions expect.
The idea
A max-heap keeps its largest element at index 0. If you swap that element with the last element of the heap, the largest value is already in its final sorted position. Then you shrink the heap by one slot and repair the root with sift_down. Repeating this n-1 times leaves the array sorted in ascending order.
So heap sort has two phases:
- Build a max-heap from the unsorted array (bottom-up, O(n)).
- Repeatedly swap the root with the last heap element, shrink the heap size by one, and sift the new root down.
The array is split into two regions that move against each other. The heap occupies a[0..end-1], and the sorted suffix occupies a[end..n-1]. No second array is needed.
Implementation
This version uses a max-heap, so the result is ascending. The sift_down_max function is the min-heap sift_down from the earlier chapter with the comparisons reversed. It takes the heap size n as a parameter, which is what lets the heap shrink without moving any data.
def sift_down_max(a, i, n):
while True:
l = 2 * i + 1
r = l + 1
largest = i
if l < n and a[l] > a[largest]:
largest = l
if r < n and a[r] > a[largest]:
largest = r
if largest == i:
return
a[i], a[largest] = a[largest], a[i]
i = largest
def build_max_heap(a):
n = len(a)
for i in range(n // 2 - 1, -1, -1):
sift_down_max(a, i, n)
def heap_sort(a):
build_max_heap(a)
for end in range(len(a) - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down_max(a, 0, end)
data = [4, 10, 3, 5, 1]
heap_sort(data)
print(data)The program prints [1, 3, 4, 5, 10].
The loop stops at end = 1 because a heap of one element is trivially sorted. The call sift_down_max(a, 0, end) uses end as the new heap size, so the element just placed at a[end] is never touched again.
Worked trace
Take [4, 10, 3, 5, 1]. Build phase: the non-leaf indices are 1 and 0. Index 1 (value 10) already beats its children 5 and 1. Index 0 (value 4) swaps with 10, then with 5, giving the max-heap [10, 5, 3, 4, 1].
| Step | Swap root with | Array after swap and sift | Heap size |
|---|---|---|---|
| after build | none | `[10, 5, 3, 4, 1]` | 5 |
| 1 | `a[4]` | `[5, 4, 3, 1, 10]` | 4 |
| 2 | `a[3]` | `[4, 1, 3, 5, 10]` | 3 |
| 3 | `a[2]` | `[3, 1, 4, 5, 10]` | 2 |
| 4 | `a[1]` | `[1, 3, 4, 5, 10]` | 1 |
In step 1, the root 1 sinks past its larger child 5 and then past 4. In step 3, the root 1 is compared with 3 and stays. In step 4 the heap holds one element, so only the swap is needed.
Cost analysis
Time
- Build phase. Bottom-up construction costs O(n). A node at height h costs at most h swaps, and at most ⌈n / 2^(h+1)⌉ nodes have height h. The total is n · Σ h / 2^(h+1), and that sum converges to a constant, so the total is O(n).
- Extraction phase. There are n-1 iterations. Each does one swap plus one
sift_downon a heap of size at most n, which costs at most ⌊log₂ n⌋ levels. The total is O(n log n). - Overall. O(n) + O(n log n) = O(n log n). The extraction phase dominates.
The extraction cost does not depend on input order. The element moved to the root came from the bottom of the tree, so it is usually small and sinks almost to the leaves. Sorted, reversed, and random inputs all cost Θ(n log n). The exception is an array where all keys are equal. With strict comparisons no swaps occur, and the whole sort runs in O(n).
Comparisons
Each level of a sift_down uses up to two comparisons: left against the current largest, then right against the new largest. A worst-case count is therefore about 2n log₂ n comparisons. GATE questions that ask for "number of comparisons" usually want you to trace the exact steps, not use this bound.
Space and stability
- Extra space is O(1), because the sort is in place. Your
sift_downis iterative here. A recursive version would use O(log n) stack space. - Heap sort is not stable. The long-distance swaps between the root and the last slot can move equal keys past each other. For example, sorting
[2a, 2b, 1]with a max-heap yields[1, 2b, 2a].
Choosing the heap type
Ascending order needs a max-heap, because each extracted maximum fills the array from the right. A min-heap sorts in place into descending order. If you need ascending output from a min-heap, you must either copy the extracted values into a second array, which costs O(n) extra space, or reverse the array at the end.
| Property | Heap sort | Merge sort | Quick sort |
|---|---|---|---|
| Worst-case time | O(n log n) | O(n log n) | O(n²) |
| Extra space | O(1) | O(n) | O(log n) average stack |
| Stable | No | Yes | No |
Heap sort's guaranteed bound and constant space are its selling points. In practice it is slower than quick sort, because it jumps between distant array positions and uses the cache poorly.
Common errors
- Forgetting to shrink the heap. Calling
sift_down_max(a, 0, len(a))inside the loop lets the root sink into the sorted suffix and ruins the result. - Starting the build loop at the wrong index. The last non-leaf is
n // 2 - 1for 0-based arrays. Starting atn // 2skips one node, and starting atnwastes work on leaves. - Mixing index bases. In a 1-based exam question the children of
iare2iand2i+1, and the last non-leaf is⌊n/2⌋. Check which convention the question uses before tracing. - Claiming O(n log n) for the build phase. The bound is correct but loose. The tight bound is O(n).
Exercises
Exercise
Apply heap sort (max-heap, ascending) to [3, 1, 6, 2]. Give the array after the build phase and after the first extraction step (swap and sift).
Show answer
Build: the non-leaf indices are 1 and 0. Index 1 (value 1) has the single child a[3]=2, so it swaps, giving [3, 2, 6, 1]. Index 0 (value 3) has children 2 and 6, so it swaps with 6, giving [6, 2, 3, 1]. After build the array is [6, 2, 3, 1]. First extraction: swap a[0] and a[3] to get [1, 2, 3, 6], then sift down the root within heap size 3. The children are 2 and 3, so the root swaps with 3, giving [3, 2, 1, 6].
Exercise
A sorted ascending array of n distinct keys is given to heap sort. What are the time complexities of the build phase and of the whole sort, and why is the whole sort not faster than on random input?
Show answer
The build phase is O(n) and the whole sort is Θ(n log n). Sorted input is not a max-heap, so the build phase must move large keys up. During extraction, the element moved to the root is taken from the last position and sinks almost to the bottom no matter what the input order was. Each of the n-1 extractions therefore costs about log n, and the input order gives no savings.