Binary heaps and priority queues
A binary heap combines complete-tree shape with a parent-child priority rule. The array fixes the shape; swaps restore order. A heap is not sorted across a level or between unrelated subtrees.
9.1 Array geometry and extreme keys
Past papers · CS 2014–2026 (23 papers): 7 questions, 10 marks
A min-heap has each parent key no greater than either child. A max-heap has each parent key no smaller. Equality is permitted unless the question explicitly says keys are distinct.
With distinct keys, the second smallest key of a min-heap is a child of its root; the maximum must be among the leaves. Therefore finding that maximum requires comparisons in the worst case, not a logarithmic root-to-leaf walk. With ties, a maximum also occurs at a leaf, but can additionally occur at an internal node.
For distinct keys, the key of ascending rank in a min-heap has depth at most because every ancestor is smaller. The mirrored statement holds for descending ranks in a max-heap. This is a bound on position, not a search algorithm.
9.2 Updating and building heaps
Past papers · CS 2014–2026 (23 papers): 8 questions, 13 marks
| Operation | Method | Worst-case time |
|---|---|---|
| Inspect extreme | Read root | |
| Insert | Append at next complete-tree position; sift up | |
| Extract extreme | Move last item to root; shrink; sift down | |
| Delete known index | Replace by last item; sift up or down as needed | |
| Change known key | Sift in the direction of the violation | |
| Search arbitrary key | No full ordering; may inspect all items | |
| Bottom-up build | Sift down from last internal node to root | |
| Meld two array heaps | Concatenate arrays and rebuild |
For min-heap sift-down, swap with the smaller child when the parent violates order; use the larger child for max-heaps. A replacement after arbitrary-index deletion may violate the parent relation, so always sifting downward is wrong. If only a key is supplied, add the cost of locating its index.
Repeated root extraction after building a max-heap sorts an array in ascending order in worst-case time; heapsort and comparison lower bounds are covered in Algorithms. A heap can be built from any tree's collected keys in linear time; producing a BST from an arbitrary heap requires comparison sorting in the general case, so linear conversion is not generally possible.
9.3 Counting heaps
Past papers · CS 2014–2026 (23 papers): 1 question, 2 marks
Last-minute recall
- A heap needs both shape and priority invariants.
- Check whether the array is zero- or one-based.
- Extreme key is at root; the opposite extreme needs a leaf scan.
- Use the more extreme child when sifting down.
- Arbitrary-index deletion can need sift-up.
- Bottom-up construction is linear.
- Count heaps on their complete shape, not all binary-tree shapes.