Sub topic 11
Heap sort
This chapter assumes you know Python lists and loops, zero-based array indexing, parent and child positions in a binary tree, and O(log n) notation. It also assumes you have seen how a binary heap sifts items up and down.
The idea
Heap sort turns a list into a heap, then removes the largest item again and again. Each removed item goes into the spot the heap just freed at the end of the list. Because the sorted part grows inside the same list, no extra array is needed.
The algorithm has two phases.
- Build a max-heap from the whole list. The largest value is now at index 0.
- Swap index 0 with the last index of the heap region. Shrink the region by one. Sift the new root down to restore the heap. Repeat until the region has one item.
A max-heap is used because the largest value goes to the end of the list. That gives ascending order.
The code
def _sift_down_max(a, i, n):
while True:
largest = i
left = 2 * i + 1
right = left + 1
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_max(a, i, n)
for end in range(n - 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) # [1, 3, 4, 5, 10]_sift_down_max takes the heap size n as a parameter. During phase 2, the heap region is a[0:end], and everything from end onward is already sorted. Passing end as the size keeps the sift from touching sorted items.
Phase 1: building the heap
The first loop starts at n // 2 - 1, the last index that has a child. Indexes after it are leaves, and a leaf is already a valid one-item heap. Going backward guarantees that both subtrees of each node are heaps before that node is sifted down. This is the bottom-up build from the previous chapters, and it costs O(n).
Phase 2: extracting
Take [4, 10, 3, 5, 1]. After phase 1 the list is [10, 5, 3, 4, 1].
- Swap 10 with 1, giving
[1, 5, 3, 4 | 10]. Sift 1 down within the first four items:[5, 4, 3, 1 | 10]. - Swap 5 with 1, giving
[1, 4, 3 | 5, 10]. Sift down:[4, 1, 3 | 5, 10]. - Swap 4 with 3, giving
[3, 1 | 4, 5, 10]. Sift down: no change. - Swap 3 with 1, giving
[1 | 3, 4, 5, 10]. Done.
Cost and trade-offs
Phase 1 costs O(n). Phase 2 runs n - 1 sift-downs of O(log n) each, so the total is O(n log n) in the best, average, and worst cases. Extra space is O(1).
| Property | Heap sort |
|---|---|
| Worst-case time | O(n log n) |
| Extra space | O(1) |
| Stable | No |
Common errors
- Using a min-heap and expecting ascending output. You would get descending order, or you would have to reverse the result.
- Sifting down with the full length
nin phase 2. The sift then pulls sorted items back into the heap. - Starting phase 1 at
n - 1or at index 0 and going forward. Parents must be fixed after their children. - Expecting stability. Swaps move equal items past each other, so their original order is not kept.
Exercise
In phase 2, why does the loop call _sift_down_max(a, 0, end) instead of _sift_down_max(a, 0, n)?
Show answer
After the swap, positions end and beyond hold the largest items in their final sorted places. Passing end as the heap size makes the sift ignore them. Passing n would let the sift compare against sorted items and move them back into the heap, breaking the sort.
Exercise
Sort [2, 1, 2'], where 2' is a second 2 that came later. Can heap sort end with 2' before 2? What does this say about stability?
Show answer
Yes. After building the max-heap, 2 is at the root. The first swap sends 2 to the end, so 2 lands after 2', reversing their original order. Heap sort is not stable.