Sub topic 14
Heap Sort
This chapter assumes you know how a binary heap is stored in an array and how heap construction works, as covered in the previous chapter. It also assumes you can solve simple recurrences and sums. The chapter shows how a heap turns into an in-place sorting algorithm, and it lists the properties GATE asks about.
The idea
A max-heap keeps its largest element at index 0. Heap sort uses this in two phases:
- Build a max-heap from the array in place.
- Repeat: swap the root (the maximum) with the last element of the heap, shrink the heap by one, and restore the heap property by sifting the new root down.
Each swap puts the current maximum in its final position at the end of the array. The sorted region grows from the right while the heap shrinks on the left. Ascending order needs a max-heap. A min-heap would give descending order when sorted in place this way.
Implementation
Indices are 0-based. The children of node i are 2i+1 and 2i+2. The last internal node is at index n//2 - 1.
def sift_down(a, i, n):
"""Restore the max-heap property for the subtree rooted at i,
considering only a[0:n]."""
while True:
left = 2 * i + 1
right = left + 1
largest = i
if left < n and a[left] > a[largest]:
largest = left
if right < n and a[right] > a[largest]:
largest = right
if largest == i:
return
a[i], a[largest] = a[largest], a[i]
i = largest
def heap_sort(a):
n = len(a)
for i in range(n // 2 - 1, -1, -1):
sift_down(a, i, n)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(a, 0, end)
data = [4, 10, 3, 5, 1]
heap_sort(data)
print(data) # [1, 3, 4, 5, 10]The n parameter of sift_down is the current heap size. After each extraction, the elements from index end onward are already sorted and must not be touched.
Worked trace
Take [4, 10, 3, 5, 1].
Build phase. n = 5, so i runs from 1 down to 0.
i = 1: the value 10 is larger than its children 5 and 1, so nothing changes.i = 0: the value 4 swaps with its larger child 10, giving[10, 4, 3, 5, 1]. Then 4 at index 1 swaps with 5, giving[10, 5, 3, 4, 1].
Extraction phase.
| Step | Array after swap | Array after sift-down | Heap size |
|---|---|---|---|
| 1 | `[1, 5, 3, 4, 10]` | `[5, 4, 3, 1, 10]` | 4 |
| 2 | `[1, 4, 3, 5, 10]` | `[4, 1, 3, 5, 10]` | 3 |
| 3 | `[3, 1, 4, 5, 10]` | `[3, 1, 4, 5, 10]` | 2 |
| 4 | `[1, 3, 4, 5, 10]` | `[1, 3, 4, 5, 10]` | 1 |
Complexity
- Build phase: Θ(n). Most nodes sit near the bottom and sift down only a few levels. The sum of heights over all nodes is bounded by n.
- Extraction phase: n − 1 sift-downs. Each costs at most the heap height, which is at most ⌊log₂ n⌋. The total is O(n log n).
- Overall: Θ(n log n) in the best, average, and worst cases. Θ(n) for the build plus Θ(n log n) for extraction still gives Θ(n log n).
- Space: O(1) extra, because the sort happens inside the input array.
Heap sort has no bad input like quick sort's sorted array. Its worst case is guaranteed O(n log n). If all keys are equal, the sift-downs stop immediately, and the extraction phase drops to Θ(n). In general, though, every input costs about n log n.
Properties
| Property | Heap sort |
|---|---|
| Worst-case time | Θ(n log n) |
| Extra space | O(1), in-place |
| Stable | No |
| Adaptive | No (sorted input is not faster) |
| Comparison-based | Yes |
Why it is not stable. Swapping the root with the last element moves equal keys across each other. Let 2a and 2b be two records with key 2, and let 1c have key 1. Start with [2a, 2b, 1c], which is already a valid max-heap. The first extraction swaps 2a with 1c, giving [1c, 2b, 2a]. After sifting down, 2b becomes the root: [2b, 1c, 2a]. The second extraction swaps 2b with 1c. The final order is 1c, 2b, 2a, so 2a and 2b have changed their relative order.
Common errors
- Starting the build at the wrong index. Leaves are already heaps. Starting at
n//2 - 1is correct. Starting atn - 1wastes work, and starting at 0 only gives an invalid heap. - Building by repeated insertion. That costs O(n log n) for the build, so it works but loses the O(n) bound. Sift-down construction is the O(n) method.
- Forgetting to shrink the heap bound. If
sift_downstill sees the sorted tail, it will pull sorted elements back into the heap. - Building a min-heap for ascending output. This leaves the array in descending order.
- Assuming the array is sorted partway through. After the build phase the array is only heap-ordered. Only the tail is sorted during extraction.
Exercises
Exercise
Build a max-heap from [3, 9, 2, 7, 6] using the bottom-up sift-down method. What is the array after the build phase, and after the first extraction (swap and sift-down)?
Show answer
With n = 5, start at i = 1. The value 9 is larger than its children 7 and 6, so there is no change. At i = 0, 3 swaps with 9, giving [9, 3, 2, 7, 6]. Then 3 at index 1 swaps with 7, giving [9, 7, 2, 3, 6]. That is the heap after the build phase. The first extraction swaps 9 with 6, giving [6, 7, 2, 3, 9]. Sifting down in a heap of size 4, 6 swaps with 7, giving [7, 6, 2, 3, 9]. Index 3 is a child of index 1, and 3 < 6, so it stops.
Exercise
A sorted array of n distinct keys is given to heap sort and to quick sort with the last element as pivot. Give the time complexity of each.
Show answer
Heap sort takes Θ(n log n), because the build phase and the n − 1 extractions cost the same regardless of input order. Quick sort with a last-element pivot on a sorted array always picks the largest element, so the recurrence is T(n) = T(n − 1) + Θ(n), which is Θ(n²).