Sub topic 2
Building a Max-Heap from an Unsorted Array
This chapter assumes you know Python, zero-based arrays, and Big-O notation. It also assumes you know the parent and child index formulas and the max-heap property from the previous chapter.
Building the Heap Bottom-Up
Leaves are trivially valid heaps. The last non-leaf node sits at index n // 2 - 1. If you run sift-down on each node from that index back to the root, every subtree below a node is already a heap by the time that node is processed.
def sift_down(a, start, end):
root = start
while True:
child = 2 * root + 1
if child >= end:
break
if child + 1 < end and a[child + 1] > a[child]:
child += 1
if a[root] >= a[child]:
break
a[root], a[child] = a[child], a[root]
root = child
def build_max_heap(a):
n = len(a)
for start in range(n // 2 - 1, -1, -1):
sift_down(a, start, 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(a, 0, end)
data = [5, 2, 9, 1, 7, 3]
heap_sort(data)
print(data) # [1, 2, 3, 5, 7, 9]Swap the Root, Shrink, Repeat
After the build, a[0] holds the maximum. Swap it into the last slot of the heap, shrink the heap by one by passing end to sift-down, and sift the new root down. The sorted suffix grows from the right.
Tracing an Example
Building from [5, 2, 9, 1, 7, 3] gives the heap [9, 7, 5, 1, 2, 3]. In the array column, the values after the bar are the sorted suffix.
| end | After swap | After sift-down | Column | Column |
|---|---|---|---|---|
| 5 | [3, 7, 5, 1, 2 \ | 9] | [7, 3, 5, 1, 2 \ | 9] |
| 4 | [2, 3, 5, 1 \ | 7, 9] | [5, 3, 2, 1 \ | 7, 9] |
| 3 | [1, 3, 2 \ | 5, 7, 9] | [3, 1, 2 \ | 5, 7, 9] |
| 2 | [2, 1 \ | 3, 5, 7, 9] | [2, 1 \ | 3, 5, 7, 9] |
| 1 | [1 \ | 2, 3, 5, 7, 9] | [1, 2, 3, 5, 7, 9] |
Time and Space Complexity
| Phase | Cost |
|---|---|
| Build heap | O(n) |
| n − 1 extractions, each O(log n) | O(n log n) |
| Total, best/average/worst (distinct keys) | O(n log n) |
| Extra space | O(1) |
Space stays at O(1) because sift_down is iterative and the sort swaps elements within the input array. With many equal keys, sift-down can stop early. In the extreme case where all keys are equal, the sort runs in O(n).
Exercise
What array does buildmaxheap produce from [1, 2, 3, 4, 5]?
Show answer
[5, 4, 3, 1, 2]. At index 1, the value 2 swaps with its larger child 5, giving [1, 5, 3, 4, 2]. At index 0, the value 1 swaps with 5 and then with 4, giving [5, 4, 3, 1, 2].