Sub topic 13
Binary Heaps and Building a Heap in O(n)
This chapter assumes you know asymptotic notation (O, Omega, Theta), can sum simple series, and are comfortable with arrays and recursion. Heap sort is the next chapter. Here we build the structure it depends on and prove that building a heap takes linear time.
What a binary heap is
A binary heap is a complete binary tree stored in an array that satisfies the heap-order property. A tree is complete when every level is full except possibly the last, and the last level is filled from the left.
- In a max-heap, every node is greater than or equal to its children. The maximum sits at the root.
- In a min-heap, every node is less than or equal to its children. The minimum sits at the root.
Heap order only relates a parent to its children. It does not order siblings, so a heap is not a sorted structure and not a search tree.
Array layout
Because the tree is complete, no pointers are needed. With 0-based indexing, for node i:
| Relation | Index |
|---|---|
| Parent | `(i - 1) // 2` |
| Left child | `2*i + 1` |
| Right child | `2*i + 2` |
With 1-based indexing, as in many GATE questions, the formulas are i/2, 2i, and 2i + 1. Check which convention a question uses before you compute anything.
The array [90, 70, 80, 30, 60, 40, 50] is a valid max-heap. Index 0 holds 90. Its children at indexes 1 and 2 are 70 and 80, and both are at most 90.
Height and node counts
A heap with n nodes has height floor(log2 n), where height counts edges on the longest root-to-leaf path. Two facts matter for the analysis below.
- The leaves occupy indexes from floor(n/2) to n - 1 (0-based). So about half the nodes are leaves.
- A heap with n nodes has at most ceil(n / 2^(h+1)) nodes of height h.
Heapify (sift down)
max_heapify(a, i, n) assumes the subtrees rooted at the children of i are already max-heaps, but a[i] may be smaller than a child. It swaps a[i] with its larger child and repeats down the tree until heap order holds.
Its cost is proportional to the height of node i, so it is O(log n) in the worst case. More precisely it is O(h), where h is the height of node i.
def max_heapify(a, i, n):
while True:
largest = i
left, right = 2 * i + 1, 2 * i + 2
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 = largestBuilding a heap bottom-up
To turn an arbitrary array into a heap, call max_heapify on every internal node, from the last one back to the root. Leaves are already one-element heaps, so we skip them.
def build_max_heap(a):
n = len(a)
for i in range(n // 2 - 1, -1, -1):
max_heapify(a, i, n)
return a
print(build_max_heap([4, 10, 3, 5, 1, 8, 7]))This prints [10, 5, 8, 4, 1, 3, 7]. Going from the bottom up guarantees that when we heapify node i, both child subtrees are already heaps. This is the precondition max_heapify needs.
Why building is O(n), not O(n log n)
A quick bound gives n/2 calls at O(log n) each, so O(n log n). That is correct but not tight. Most calls are on nodes near the bottom, where the height is small.
Count the work by height. At most ceil(n / 2^(h+1)) nodes have height h, and each costs O(h). The total is
T(n) = sum over h = 0 to floor(log2 n) of ceil(n / 2^(h+1)) O(h) = O(n sum over h of h / 2^h).
The infinite series sum over h >= 0 of h / 2^h converges to 2. (Using sum of h x^h = x / (1 - x)^2 at x = 1/2 gives (1/2) / (1/4) = 2.) So the total is O(n 2) = O(n). Since every element must be examined, the bound is also Omega(n), so building a heap is Theta(n).
Intuition: half the nodes cost 0 swaps, a quarter cost at most 1, an eighth at most 2, and so on. The deep, expensive nodes are very rare.
Other heap operations
| Operation | Method | Worst-case time |
|---|---|---|
| Find max (or min) | Read the root | O(1) |
| Insert | Append at the end, sift up | O(log n) |
| Extract max | Swap root with last, shrink, heapify root | O(log n) |
| Increase key (max-heap) | Change value, sift up | O(log n) |
| Delete arbitrary node | Replace with last, then sift up or down | O(log n) |
| Search for an arbitrary key | Scan the array | O(n) |
| Build heap from n keys | Bottom-up heapify | Theta(n) |
Sift-up moves a new element toward the root while it is larger than its parent:
def heap_insert(a, key):
a.append(key)
i = len(a) - 1
while i > 0 and a[(i - 1) // 2] < a[i]:
p = (i - 1) // 2
a[p], a[i] = a[i], a[p]
i = pBuilding by repeated insertion is different
If you instead insert n keys one at a time, each insert costs O(log n), giving O(n log n) in the worst case. Inserting keys in increasing order into a max-heap forces every new key to travel to the root, which costs Theta(n log n) in total. Bottom-up construction is asymptotically faster, and this contrast is a common GATE question.
Common errors
- Heapifying from the root downward. The precondition fails because the subtrees are not heaps yet.
- Starting the loop at
n - 1or skipping the correct start index. The last internal node isn // 2 - 1(0-based) orfloor(n/2)(1-based). - Assuming the second-largest element is the last array position. It is one of the root's two children.
- Assuming the minimum of a max-heap is at index 1. It is somewhere among the leaves, so finding it takes O(n).
- Counting height in nodes instead of edges when applying the formula floor(log2 n).
Worked trace
Build a max-heap from [4, 10, 3, 5, 1, 8, 7] (n = 7). The last internal node is index 2.
- Heapify index 2 (value 3): children are 8 and 7. Swap with 8. Array:
[4, 10, 8, 5, 1, 3, 7]. - Heapify index 1 (value 10): children are 5 and 1. Already in order. No change.
- Heapify index 0 (value 4): children are 10 and 8. Swap with 10, giving
[10, 4, 8, 5, 1, 3, 7]. Now 4 sits at index 1 with children 5 and 1. Swap with 5. Array:[10, 5, 8, 4, 1, 3, 7].
The result matches the program output above, using 4 swaps in total.
Exercise
A max-heap stored 1-based in an array has 100 elements. Which positions can hold the minimum element, and what is the cost of finding it?
Show answer
The minimum must be a leaf. With 1-based indexing the leaves are positions 51 to 100, because the last internal node is floor(100/2) = 50. The heap order gives no information among leaves, so you must scan all of them. Finding the minimum costs Theta(n) (about n/2 comparisons).
Exercise
Show that the number of nodes of height h in an n-node heap is at most ceil(n / 2^(h+1)), then use it to explain why buildmaxheap runs in O(n) and not just O(n log n).
Show answer
Nodes of height 0 are the leaves, about n/2 of them. Removing all leaves leaves a heap with about n/2 nodes whose leaves are exactly the nodes of height 1, so there are about n/4 of them. Repeating gives n / 2^(h+1) nodes of height h. Heapify on a node of height h costs O(h), so the total is the sum over h of (n / 2^(h+1)) O(h) = O(n sum of h/2^h) = O(2n) = O(n). The n log n bound treats every call as if it cost log n, but only the root costs that much.
Exercise
Build a min-heap from [9, 4, 7, 1, 6, 2] using the bottom-up method. Give the final array.
Show answer
n = 6, so the last internal node is index 2 (0-based). Heapify index 2 (value 7): its only child at index 5 is 2, so swap to get [9, 4, 2, 1, 6, 7]. Heapify index 1 (value 4): children are 1 and 6, swap with 1 to get [9, 1, 2, 4, 6, 7]. Heapify index 0 (value 9): children are 1 and 2, swap with 1 to get [1, 9, 2, 4, 6, 7]. Now 9 at index 1 has children 4 and 6, swap with 4 to get [1, 4, 2, 9, 6, 7]. The final array is [1, 4, 2, 9, 6, 7].