Sub topic 16
Building a Heap in O(n)
Prerequisites and the bottom-up idea
Assume you know arrays, zero-based indexing, loops, binary trees, and Big-O notation. A binary heap is a complete binary tree stored in an array. In a min-heap, every parent is less than or equal to its children.
For an element at index i:
- Left child:
2i + 1 - Right child:
2i + 2 - Parent:
(i - 1) // 2
The leaves already satisfy the heap condition because they have no children. Therefore, bottom-up construction only needs to repair internal nodes. The last internal node is at index n // 2 - 1.
For each internal node, apply sift down. Sift down moves a value toward the leaves until it is no greater than both children.
def sift_down(a, i, n):
while True:
left = 2 * i + 1
right = left + 1
smallest = i
if left < n and a[left] < a[smallest]:
smallest = left
if right < n and a[right] < a[smallest]:
smallest = right
if smallest == i:
return
a[i], a[smallest] = a[smallest], a[i]
i = smallest
def build_min_heap(a):
for i in range(len(a) // 2 - 1, -1, -1):
sift_down(a, i, len(a))
values = [9, 4, 7, 1, 3, 6, 2]
build_min_heap(values)
print(values)The output is:
[1, 3, 2, 4, 9, 6, 7]The exact arrangement can differ when values are equal, but every parent must be no greater than its children.
Why the cost is O(n)
A common mistake is to say that there are n nodes and each sift down costs O(log n), so construction costs O(n log n). That treats every node as if it were near the root.
Most nodes are near the bottom and can move only a short distance. The number of nodes that can move at least h levels decreases by about half for each additional level. The total work is bounded by:
n/2 · 0 + n/4 · 1 + n/8 · 2 + n/16 · 3 + ...
This sum is less than a constant multiple of n, so bottom-up construction takes O(n) time. It modifies the existing array and uses O(1) extra space, excluding the input array.
Trace the construction order
For [9, 4, 7, 1, 3, 6, 2], n = 7, so the last internal index is 7 // 2 - 1 = 2. Sift down runs at indices 2, 1, and 0, in that order.
Exercise
Why does bottom-up construction start at index n // 2 - 1 instead of at the last array index?
Show answer
Indices from n // 2 through n - 1 are leaves. They have no children, so they already satisfy the heap condition.