Sub topic 12
Binary Heaps and Building a Heap in O(n)
Prerequisites and Heap Representation
Assume you know arrays, zero-based indexing, logarithms, and the meaning of asymptotic time complexity. A binary heap is a nearly complete binary tree stored in an array. “Nearly complete” means every level is full except possibly the last, which is filled from left to right.
For an array index i:
- Parent:
(i - 1) // 2 - Left child:
2 * i + 1 - Right child:
2 * i + 2
A max heap has each parent greater than or equal to its children. The largest value is therefore at index 0. A min heap reverses the relation, so the smallest value is at the root.
Sifting Down
When a node may be smaller than one of its children, restore the max-heap property by sifting down. Compare the node with its children, exchange it with the larger child, and continue. The height of a heap with n elements is Theta(log n), so one sift-down operation costs O(log n).
To build a heap, call sift-down on every internal node, starting with the last internal node and moving toward the root. The last internal node is at index n // 2 - 1.
Although this performs many sift-down operations, the total cost is O(n), not O(n log n). Most nodes are near the leaves and can move only a short distance. The total can be bounded by
n/2 * O(1) + n/4 * O(2) + n/8 * O(3) + ... = O(n).
def build_max_heap(a):
def sift_down(i, size):
while True:
largest = i
left = 2 * i + 1
right = left + 1
if left < size and a[left] > a[largest]:
largest = left
if right < size and a[right] > a[largest]:
largest = right
if largest == i:
return
a[i], a[largest] = a[largest], a[i]
i = largest
for i in range(len(a) // 2 - 1, -1, -1):
sift_down(i, len(a))
values = [4, 10, 3, 5, 1]
build_max_heap(values)
print(values)Heap Sort
Heap sort first builds a max heap. It then swaps the root, which is the largest remaining value, with the final element in the active heap. The active heap becomes one position shorter, and the new root is sifted down. Repeating this produces ascending order.
Heap sort takes O(n) to build the heap and O(n log n) for n removals. It uses O(1) auxiliary space because sorting occurs in the input array. Standard heap sort is not stable.
| Property | Heap sort |
|---|---|
| Worst-case time | `O(n log n)` |
| Extra space | `O(1)` |
| Stable | No |
| In-place | Yes |
Exercise
Why does bottom-up heap construction run in O(n) rather than O(n log n)?
Show answer
Most nodes have small heights, so only a few nodes can require long sift-down operations. Summing the work by node height gives a convergent weighted series bounded by O(n).