Sub topic 15
Heap insert, extract-min/max, and sift operations
This chapter assumes you know the binary heap layout from the previous chapter: a complete binary tree stored in an array, where the key at each node is no larger than its children (min-heap) or no smaller (max-heap). It also assumes introductory Big-O and basic Python. Indices are 0-based throughout, so the children of index i are 2i+1 and 2i+2, and the parent of index i is (i-1)//2.
The idea: break the property in one place, then repair it
A heap supports two core updates. Each update first keeps the tree complete by touching only the last array position. That step may break the heap property at one spot. The repair then walks along a single root-to-leaf path.
- Insert adds the key at the end, which may leave it smaller than its parent. It repairs this by moving the key up. This repair is called sift up (also called percolate up or bubble up).
- Extract-min (in a min-heap) removes the root, moves the last element to the root, and may leave it larger than its children. It repairs this by moving the key down. This repair is called sift down (also called heapify or percolate down).
Because the tree is complete, its height is floor(log2 n). A path has at most that many edges, so both operations take O(log n) time. Reading the minimum without removing it is O(1), since it sits at index 0.
Insert and sift up
Sift up compares the new key with its parent. If the key is smaller (min-heap), they swap, and the comparison repeats from the parent's position. It stops when the parent is smaller or equal, or when the key reaches the root.
Extract-min and sift down
Sift down compares a node with both children and swaps it with the smaller child. Choosing the smaller child matters. If you swapped with the larger child, that larger child would become the parent of the smaller one, which breaks the heap property.
The code below includes both operations. sift_down takes the heap size n as a parameter, so it can work on a prefix of the array. Heap sort relies on this later.
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 heap_insert(a, x):
a.append(x)
i = len(a) - 1
while i > 0:
p = (i - 1) // 2
if a[p] <= a[i]:
break
a[p], a[i] = a[i], a[p]
i = p
def extract_min(a):
top = a[0]
last = a.pop()
if a:
a[0] = last
sift_down(a, 0, len(a))
return top
heap = []
for key in [20, 15, 30, 10, 5]:
heap_insert(heap, key)
print(heap)
print("min:", extract_min(heap))
print(heap)Worked trace: insertion
Insert 20, 15, 30, 10, 5 into an empty min-heap.
- Insert 20:
[20]. - Insert 15: append gives
[20, 15]. Parent of index 1 is index 0 (value 20). Since 15 < 20, swap:[15, 20]. - Insert 30: append gives
[15, 20, 30]. Parent is 15, which is smaller, so no swap. - Insert 10: append at index 3 gives
[15, 20, 30, 10]. Parent index 1 holds 20, so swap:[15, 10, 30, 20]. Now at index 1, parent index 0 holds 15, so swap:[10, 15, 30, 20]. - Insert 5: append at index 4 gives
[10, 15, 30, 20, 5]. Parent index 1 holds 15, so swap:[10, 5, 30, 20, 15]. Parent index 0 holds 10, so swap:[5, 10, 30, 20, 15].
The final heap is [5, 10, 30, 20, 15].
Worked trace: extract-min
Extract from [5, 10, 30, 20, 15].
- Save the root, 5. Remove the last element, 15, and place it at index 0:
[15, 10, 30, 20]. - Children of index 0 are 10 and 30. The smaller is 10, and 10 < 15, so swap:
[10, 15, 30, 20]. - At index 1, the children are index 3 (value 20) and index 4 (out of range). 20 > 15, so stop.
The result is [10, 15, 30, 20], and the function returns 5.
Costs and where they come from
| Operation | Worst case | Why |
|---|---|---|
| Peek min/max | O(1) | Root at index 0 |
| Insert | O(log n) | One path of at most floor(log2 n) swaps |
| Extract-min/max | O(log n) | Sift down along one path; up to 2 comparisons per level |
| Search for arbitrary key | O(n) | The heap property gives no ordering between siblings |
| Delete arbitrary key (position known) | O(log n) | Replace with last element, then sift up or down |
Inserting into a heap has an average case that is better than its worst case. For random keys, a new key typically moves up only a constant number of levels, so the expected cost is O(1). The worst case, such as inserting a new minimum, is still O(log n). GATE questions usually ask for the worst case unless they say otherwise.
Extract uses about 2 log2 n comparisons in the worst case: two per level (left against current, right against the smaller), over up to floor(log2 n) levels. Insert uses at most floor(log2 n) comparisons, one per level. Questions that count comparisons or swaps depend on this difference.
Edge cases and common errors
- Extract from an empty heap.
a[0]raisesIndexError. This is heap underflow, and real code should check first. - Single element. After
a.pop()the list is empty, so the code skips the placement step. Without theif a:check,a[0] = lastwould fail on an empty list. - Wrong child with one child only. A node may have a left child but no right child (only in the last internal node). The bounds check
r < nhandles this. - Ties. Use
<=in sift up and<in sift down comparisons as shown, so equal keys do not swap needlessly. A heap is not stable, so equal keys can come out in any order. - Max-heap. Flip every comparison. For example, sift down swaps with the larger child.
- Off-by-one on indexing. Many textbooks and GATE questions use 1-based arrays, where children are
2iand2i+1and the parent isi // 2. Check which convention the question uses before computing positions. - Changing a key in place. If you lower a key in a min-heap, sift it up. If you raise it, sift it down. Doing only one direction leaves the heap broken when the change goes the other way.
The array after operations is not unique
A set of keys can form several valid heaps. The final array depends on the insertion order. Inserting the same keys in a different order can produce a different array. A GATE question that shows a heap array and asks for the result of an operation expects you to apply the exact algorithm above, not just any valid heap.
A small max-heap check
For a max-heap, the same functions work with the comparisons reversed. The sketch below does so by negating keys, which is a common trick when only a min-heap is available.
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 heap_insert(a, x):
a.append(x)
i = len(a) - 1
while i > 0:
p = (i - 1) // 2
if a[p] <= a[i]:
break
a[p], a[i] = a[i], a[p]
i = p
def extract_min(a):
top = a[0]
last = a.pop()
if a:
a[0] = last
sift_down(a, 0, len(a))
return top
h = []
for key in [4, 9, 2, 7]:
heap_insert(h, -key)
print(-extract_min(h))This prints 9, the largest key.
Exercise
A min-heap is stored 0-based as [3, 8, 5, 12, 10, 9]. Insert 2, then perform one extract-min. Give the final array and state how many swaps occurred in total.
Show answer
Insert 2: append gives [3, 8, 5, 12, 10, 9, 2]. Index 6 has parent index 2 (value 5), so swap: [3, 8, 2, 12, 10, 9, 5]. Index 2 has parent index 0 (value 3), so swap: [2, 8, 3, 12, 10, 9, 5]. That is 2 swaps. Extract-min returns 2. Move the last element 5 to the root: [5, 8, 3, 12, 10, 9]. Children of index 0 are 8 and 3, and the smaller is 3, so swap: [3, 8, 5, 12, 10, 9]. At index 2, the left child index 5 holds 9, which is greater than 5, and index 6 is out of range, so stop. That is 1 swap. The final array is [3, 8, 5, 12, 10, 9], with 3 swaps in total.
Exercise
In a heap of n = 1023 keys, what is the maximum number of key comparisons that one extract-min can need, counting both child comparisons per level?
Show answer
The height is floor(log2 1023) = 9. The root moved down at most 9 levels, but a node at the last internal level has children that are leaves. Each sift-down step compares the two children and then compares the smaller child with the current node, so at most 2 comparisons per level. The maximum is 2 x 9 = 18 comparisons.
Exercise
Why does sift down swap with the smaller child in a min-heap, and what breaks if it swaps with the larger child?
Show answer
After the swap, the chosen child becomes the parent of the other child. If the larger child were promoted, it would sit above the smaller sibling, so the parent would be larger than its child. That violates the min-heap property. Promoting the smaller child keeps it no larger than both the old parent's value (now below it) and its former sibling.