Sub topic 17
Heap Sort: Algorithm and Cost
Assume you know arrays, binary heaps, zero-based indexing, and Big-O notation. Heap sort combines bottom-up heap construction with repeated removal of the largest element.
Working model
For ascending order, heap sort uses a max-heap. A max-heap is a complete binary tree in which every parent is at least as large as its children. In an array, the children of index i are:
- Left child:
2i + 1 - Right child:
2i + 2 - Parent:
(i - 1) // 2
First, the input array becomes a max-heap. The largest value is then at index 0. Swap it with the last item in the unsorted region, reduce the heap size by one, and restore the heap property by sifting the new root downward.
def sift_down(a, i, 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)
# Build a max-heap.
for i in range(n // 2 - 1, -1, -1):
sift_down(a, i, n)
# Move the maximum to its final position.
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(a, 0, end)
values = [4, 10, 3, 5, 1]
heap_sort(values)
print(values) # [1, 3, 4, 5, 10]Cost and common errors
Building the heap bottom-up takes O(n) time. Although one sift-down can take O(log n), most nodes are near the leaves and move only a short distance.
The extraction loop performs n - 1 sift-down operations, each costing at most O(log n). Therefore, heap sort takes O(n log n) time in the best, average, and worst cases. It uses O(1) extra space when performed in the same array.
| Property | Heap sort |
|---|---|
| Time | `O(n log n)` |
| Extra space | `O(1)` |
| Stable? | No |
| In-place? | Yes |
A common error is using the wrong heap. A max-heap produces ascending order when its root is placed at the end. A min-heap produces descending order with the same placement strategy. Another error is passing the full array length to sift_down after an item has entered the sorted suffix.
Exercise
Why does heap sort remain O(n log n) even when the input array is already sorted?
Show answer
Heap sort still builds a heap and performs the extraction loop. It does not have a special best-case shortcut, so its time remains O(n log n).