Sub topic 15
Heap Insert, Extract-Min/Max, and Sift Operations
Assume you know arrays, loops, functions, object references, and introductory Big-O notation. A binary heap is a complete binary tree stored in an array. A min-heap keeps the smallest key at the root. A max-heap keeps the largest key at the root.
Array representation
With zero-based indexing, the relationships are:
| Node at index `i` | Index formula |
|---|---|
| Parent | `(i - 1) // 2` |
| Left child | `2 * i + 1` |
| Right child | `2 * i + 2` |
A complete tree fills every level from left to right. Therefore, no pointer fields are needed.
Insert and sift up
To insert a key, append it at the end of the array. This preserves the complete-tree shape. The new key might violate the heap property with its parent, so repeatedly swap it upward. This operation is called sift up, or bubble up.
The path from a leaf to the root has height O(log n). Thus insertion takes O(log n) time and O(1) extra space when performed in place.
Extract and sift down
To remove the minimum from a min-heap:
- Save the root.
- Move the last array element to index
0. - Remove the old last position.
- Compare the new root with its smaller child.
- Swap downward until the heap property is restored.
This is called sift down. It also takes O(log n) time. Extracting the maximum uses the same process on a max-heap.
def sift_down(a, i):
n = len(a)
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 insert(a, x):
a.append(x)
i = len(a) - 1
while i > 0:
parent = (i - 1) // 2
if a[parent] <= a[i]:
return
a[parent], a[i] = a[i], a[parent]
i = parent
def extract_min(a):
if not a:
raise IndexError("empty heap")
result = a[0]
last = a.pop()
if a:
a[0] = last
sift_down(a, 0)
return result
heap = [2, 5, 8, 10]
insert(heap, 3)
print(extract_min(heap)) # 2
print(heap)> callout note > In sift down, compare both children and choose the smaller child for a min-heap. Choosing the left child automatically can leave the heap invalid.
Common errors
- Using
(i - 1) / 2instead of integer division. - Forgetting that the last element replaces the removed root.
- Sifting in the wrong direction after an operation.
- Confusing a heap with a sorted array. Only the root is guaranteed to be globally smallest or largest.
- Reading a child index without checking that it is less than
n.
Exercise
A min-heap is [4, 7, 9, 12]. Insert 2, then extract the minimum. What value remains at the root?
Show answer
After insertion, [2, 7, 4, 12, 9]; after extracting 2 and sifting down, the root is 4.