Sub topic 16
Building a heap in O(n)
This chapter assumes you know the array layout of a binary heap (children of index i at 2i+1 and 2i+2 with 0-based indexing), the sift-down operation, and introductory Big-O. Both heap-building methods are covered here. The chapter explains why the bottom-up method costs O(n) rather than O(n log n), which is a standard GATE question.
Two ways to build a heap
You have an unordered array of n keys and want a min-heap.
- Top-down (repeated insertion). Start with an empty heap and call
heap_insertfor each key. Each insert is O(log n), so the total is O(n log n) in the worst case. - Bottom-up (Floyd's method). Treat the array as a complete binary tree already. Fix the heap property from the last non-leaf node back to the root, calling
sift_downon each one.
The bottom-up method is the one the exam calls "build heap". It does the same job in Θ(n) time.
def sift_down(a, i, n):
while True:
l = 2 * i + 1
r = l + 1
smallest = i
if l < n and a[l] < a[smallest]:
smallest = l
if r < n and a[r] < a[smallest]:
smallest = r
if smallest == i:
return
a[i], a[smallest] = a[smallest], a[i]
i = smallest
def build_min_heap(a):
n = len(a)
for i in range(n // 2 - 1, -1, -1):
sift_down(a, i, n)Why start at n // 2 - 1
In a complete binary tree stored in an array, a node at index i has a left child only if 2i + 1 < n. That means i < (n - 1) / 2, so the last node with a child is at index n // 2 - 1. Every index from n // 2 to n - 1 is a leaf. A leaf is already a valid one-node heap, so calling sift_down on it would do nothing.
With 1-based indexing the same rule reads: the last internal node is floor(n/2), and the loop runs from floor(n/2) down to 1.
Why the order matters
sift_down(a, i, n) is only correct if both subtrees of i are already heaps. Going from the last internal node back to the root guarantees this. When the loop reaches index i, every index greater than i is already the root of a valid heap, and the children of i have larger indices than i.
If you went in the opposite direction (root first), the subtrees below would not yet be heaps, and one sift would not repair the tree.
Worked trace
Build a min-heap from [9, 4, 7, 1, 6, 2, 3]. Here n = 7, so the loop starts at 7 // 2 - 1 = 2.
| Step | Index `i` | Compare with | Action | Array after |
|---|---|---|---|---|
| 1 | 2 (value 7) | children 2 and 3 | swap with 2 (index 5) | `[9, 4, 2, 1, 6, 7, 3]` |
| 2 | 1 (value 4) | children 1 and 6 | swap with 1 (index 3) | `[9, 1, 2, 4, 6, 7, 3]` |
| 3 | 0 (value 9) | children 1 and 2 | swap with 1 (index 1) | `[1, 9, 2, 4, 6, 7, 3]` |
| 3, continued | 1 (value 9) | children 4 and 6 | swap with 4 (index 3) | `[1, 4, 2, 9, 6, 7, 3]` |
The final heap is [1, 4, 2, 9, 6, 7, 3]. You can verify it: 1 has children 4 and 2, 4 has children 9 and 6, and 2 has children 7 and 3. Every parent is at most its children.
Notice that the key 9 started at the root, which is the most expensive position. It sank two levels. Keys that start near the leaves sink very little.
Why it is O(n)
The idea: sift_down costs time proportional to the height of the node, not the height of the whole tree. Most nodes are near the bottom, so most calls are cheap.
Define the height of a node as the length of the longest downward path to a leaf. Leaves have height 0. A sift_down on a node of height h makes at most h swaps, so its cost is at most c·h for a constant c.
An n-node heap has at most ceil(n / 2^(h+1)) nodes of height h. Adding up the work over all heights:
T(n) <= sum over h of ceil(n / 2^(h+1)) * c * hIgnoring the ceilings (they add at most one extra node per level, which is O(log² n) in total and negligible), this becomes:
T(n) <= c * n * sum_{h>=0} h / 2^(h+1)The series sum h / 2^h for h = 0, 1, 2, ... converges to 2. So the sum above converges to 1, and T(n) <= c·n. The cost is O(n). Because the loop visits about n/2 nodes, it is also Ω(n), so the bound is Θ(n).
Counting swaps in a perfect tree
For a perfect tree with 15 nodes, the worst case for each node is h swaps:
- Height 0: 8 nodes × 0 = 0
- Height 1: 4 nodes × 1 = 4
- Height 2: 2 nodes × 2 = 4
- Height 3: 1 node × 3 = 3
Total: 11 swaps. Repeated insertion in the worst case moves each node up by its depth: 1×0 + 2×1 + 4×2 + 8×3 = 34 swaps. The gap grows with n, because the many nodes at the bottom are the expensive ones for insertion but the cheap ones for bottom-up building.
Edge cases and common errors
- Wrong loop start. Starting at
n - 1orn // 2still gives a correct heap, since extra calls on leaves do nothing, but it wastes time and signals a misunderstanding. Starting atn // 2 - 2skips a real internal node and breaks the heap. - Off-by-one with indexing. In 1-based pseudocode the loop is
for i = floor(n/2) downto 1. In 0-based code it isn // 2 - 1. Keep the child formulas consistent with the base. - Comparisons count. Each sift step makes up to two comparisons (the two children against the current key), so bounds on comparisons are about twice the swap counts. The total stays below roughly
2n. - Different results for the same input. Repeated insertion and bottom-up building can produce different valid heaps from the same array. Only the heap property is guaranteed, not a unique layout. Exam questions that ask for the resulting array need you to use the stated method.
- Best case is not better. Even on an array that is already a heap, the loop still visits
n/2nodes and makes at least one comparison at each, so it is Θ(n) in every case. - Heap sort is still O(n log n). Building the heap is O(n), but heap sort then performs
n - 1extractions of O(log n) each. The extraction phase dominates, so the total remains O(n log n).
Quick reference
| Method | Worst-case time | Notes |
|---|---|---|
| Repeated `heap_insert` | O(n log n) | Sift-up per key, works online |
| Bottom-up `build_min_heap` | O(n) | Needs all keys up front, sift-down per internal node |
Exercise
Build a min-heap in place from the array [5, 3, 8, 1, 2] using buildminheap. Give the array after the algorithm finishes.
Show answer
Here n = 5, so the loop starts at index 5 // 2 - 1 = 1. At i = 1 (value 3), the children are 1 and 2, so swap with 1: [5, 1, 8, 3, 2]. At i = 0 (value 5), the children are 1 and 8, so swap with 1: [1, 5, 8, 3, 2]. The value 5 is now at index 1 with children 3 and 2, so swap with 2 at index 4: [1, 2, 8, 3, 5]. The result is [1, 2, 8, 3, 5].
Exercise
A perfect binary tree has 31 nodes. What is the maximum number of swaps bottom-up build_heap can make, and how many can repeated insertion make in the worst case?
Show answer
The tree has heights 0 to 4 with 16, 8, 4, 2, and 1 nodes. Bottom-up worst case is 16×0 + 8×1 + 4×2 + 2×3 + 1×4 = 26 swaps. Repeated insertion worst case moves each node up by its depth: 1×0 + 2×1 + 4×2 + 8×3 + 16×4 = 98 swaps.
Exercise
Why is the total cost of bottom-up heap construction O(n) even though each sift_down call can cost O(log n)?
Show answer
A sift_down call costs time proportional to the height of the node it starts from, not the height of the tree. About half the nodes are leaves (height 0) and need no work, a quarter have height 1, and so on. The total is proportional to n times the sum of h / 2^(h+1), which converges to n, so the cost is O(n).