Worked Examples: Heaps & Priority Queues

These examples are designed to step through the logical process of working with heap data structures.

Example 1: Array to Max-Heap Indices
❓ Problem: For array [16, 14, 10, 8, 7, 9, 3] using 1-based indexing, what are the children of node at index 2?
💡 Solution: Left child = 2×2 = 4, Right child = 2×2+1 = 5. Values: A[4]=8, A[5]=7. Parent of index 2 is floor(2/2) = 1 (value 16).
Example 2: Max-Heapify Trace
❓ Problem: Apply Max-Heapify to [4, 14, 10, 8, 7, 9, 3] at index 1 (1-based).
💡 Solution: Node 4 < children 14, 10. Swap with largest (14) → [14, 4, 10, 8, 7, 9, 3]. Now recurse at index 2. Node 4 < children 8, 7. Swap with 8 → [14, 8, 10, 4, 7, 9, 3]. Node 4 is now a leaf. Done.
Example 3: Build-Max-Heap
❓ Problem: Build a max-heap from [4, 1, 3, 2, 16, 9, 10, 14, 8, 7].
💡 Solution: Start at floor(n/2) = 5, go down to 1. Heapify at each internal node. After all heapify calls: [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]. Time: O(n), not O(n log n), because most nodes are near leaves.
Example 4: Heapsort First Step
❓ Problem: After building max-heap [16, 14, 10, 8, 7, 9, 3], what is the array after one heapsort iteration?
💡 Solution: Swap root (16) with last element (3): [3, 14, 10, 8, 7, 9, | 16]. Reduce heap size. Heapify root: 14 is largest child, swap → [14, 3, 10, 8, 7, 9 | 16]. Heapify again: [14, 8, 10, 3, 7, 9 | 16].
Example 5: Priority Queue Insert
❓ Problem: Insert 15 into max-heap [16, 14, 10, 8, 7, 9, 3].
💡 Solution: Add 15 at end: [16, 14, 10, 8, 7, 9, 3, 15]. Float up: parent of 8 (index 4) is 14 (index 2). 15 > 8, swap → [16, 14, 10, 15, 7, 9, 3, 8]. 15 > 14, swap → [16, 15, 10, 14, 7, 9, 3, 8]. 15 < 16, stop. Time: O(log n).
Example 6: Extract-Max
❓ Problem: Extract-Max from [16, 14, 10, 8, 7, 9, 3].
💡 Solution: Save max = 16. Replace root with last: [3, 14, 10, 8, 7, 9]. Heapify: 14 > 3, swap → [14, 3, 10, 8, 7, 9]. 8 > 3, swap → [14, 8, 10, 3, 7, 9]. Return 16. Time: O(log n).