Sub topic 3
Priority Queues and Binary Heaps
This chapter assumes you know arrays and zero-based indexing, Big-O notation, and basic recursion. A priority queue is an abstract data type where each element has a priority, and the element with the highest or lowest priority leaves first.
Priority queues: the abstract interface
A priority queue supports these operations:
insert(x): add an element.find_min(): return the smallest element without removing it.extract_min(): remove and return the smallest element.
Some implementations also support decrease_key, which lowers an element's priority. The interface says nothing about how the data is stored. A binary heap is the usual implementation.
Binary heaps: complete tree, heap property, array indices
A binary heap is a complete binary tree, meaning every level is full except possibly the last, which fills from left to right. A min-heap also satisfies the heap property: each parent is less than or equal to its children. The root holds the minimum.
Because the tree is complete, it fits in an array with no pointers. With zero-based indices, the parent of index i is (i - 1) // 2, and its children are 2*i + 1 and 2*i + 2.
Heap insert, extract-min, and sift operations
Insert appends the new key at the end, then sift up: it swaps the key with its parent while the parent is larger. Extract-min removes the root, moves the last element to the root, and sift down: it swaps the element with its smaller child until the heap property holds. Each operation follows one root-to-leaf path, so it costs O(log n).
Building a heap in O(n)
Inserting n keys one at a time costs O(n log n). Bottom-up construction is faster. Sift down every non-leaf node, starting from the last one and moving back to the root. Most nodes sit near the bottom and sift only a short distance, so the total work sums to O(n).
Heap sort: algorithm and cost
Heap sort builds a heap, then calls extract-min n times. Building costs O(n), and n extractions cost O(n log n) in total, so heap sort runs in O(n log n) time in every case.
def sift_up(a, i):
while i > 0:
p = (i - 1) // 2
if a[p] <= a[i]:
break
a[p], a[i] = a[i], a[p]
i = p
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 insert(a, x):
a.append(x)
sift_up(a, len(a) - 1)
def extract_min(a):
if not a:
raise IndexError('heap empty')
top = a[0]
last = a.pop()
if a:
a[0] = last
sift_down(a, 0, len(a))
return top
def build_min_heap(a):
n = len(a)
for i in range(n // 2 - 1, -1, -1):
sift_down(a, i, n)
def heap_sort(a):
build_min_heap(a)
out = []
while a:
out.append(extract_min(a))
return out
print(heap_sort([5, 3, 8, 1, 9, 2])) # [1, 2, 3, 5, 8, 9]GATE problem patterns and a structure comparison table
GATE questions often ask you to pick the right structure and count operations. The table compares the options for a priority queue.
| Structure | Insert | Extract-min | Find-min |
|---|---|---|---|
| Unsorted array | O(1) | O(n) | O(n) |
| Sorted linked list | O(n) | O(1) | O(1) |
| Binary heap | O(log n) | O(log n) | O(1) |
Watch for questions that ask for the cost of building a heap (O(n)) versus sorting with heap sort (O(n log n)). A binary heap with n nodes has height floor(log2 n).
Exercise
A binary heap holds 10 elements. What is its height, counting edges from the root to the deepest leaf?
Show answer
The height is floor(log2 10) = 3. The levels hold 1, 2, 4, and 3 nodes, so the tree reaches level 3.