Lesson 16 +30 XP

Heaps & Heap-Based Priority Queues

Heaps & Heap-Based Priority Queues

A Binary Heap is a Complete Binary Tree stored compactly in a 1D array (with zero wasted gaps) that satisfies the Heap Order Property:

  • Max-Heap: Every parent ≥ its children (global maximum at root A[0]).
  • Min-Heap: Every parent ≤ its children (global minimum at root A[0]).

Max-Heap OperationsMax-Heap Operations

1. Reheap Up (Insertion - O(log n))

  1. Append the new key at the end of the array (next available leaf slot n).
  2. Reheap Up: Compare with parent = (i - 1) / 2. While i > 0 and A[i] > A[parent] (for Max-Heap), swap and set i = parent.
  • Worked Trace: Insert 38 into Max-Heap [42, 32, 35, 19, 23, 12]:
  • Place 38 at index 6 (right child of 35 at index 2).
  • 38 > 35 → swap → [42, 32, 38, 19, 23, 12, 35].
  • Compare with root 42: 38 < 42 → stop!

2. Reheap Down (Extract Max/Min - O(log n))

  1. Save A[0] (the max/min), move the last leaf A[n - 1] to A[0], and decrement n.
  2. Reheap Down: Swap downward with the larger child (Max-Heap) or smaller child (Min-Heap) until heap order is restored.
  • Worked Trace: Deleting 42 from [42, 32, 35, 19, 23, 12]:
  • Move 12 to root → [12, 32, 35, 19, 23].
  • Larger child of 12 is 35 (index 2) → swap → [35, 32, 12, 19, 23].
  • 12 is now a leaf → stop!
C
void reheapDown(int a[], int n, int i) {
    while (2 * i + 1 < n) {
        int largest = 2 * i + 1;
        if (largest + 1 < n && a[largest + 1] > a[largest])
            largest++;
        if (a[i] >= a[largest]) break;
        int t = a[i]; a[i] = a[largest]; a[largest] = t;
        i = largest;
    }
}

3. Build-Heap &amp; Priority Queue Applications

  • Floyd's Bottom-Up Build-Heap: Calling reheapDown from the last non-leaf node (n/2 - 1) down to 0 builds a heap in O(n) time (faster than n insertions which take O(n log n) because half the nodes are leaves at height 0!).
  • Min-Heap Priority Queue: In OS task scheduling, tasks with the smallest deadline/priority number sit at A[0] for O(1) peek and O(log n) dispatch; also powers Dijkstra's shortest path and Prim's MST.

Index Rules for an Array Heap

Relation0-based array1-based array
Parent of i⌊(i − 1)/2⌋⌊i/2⌋
Left child of i2i + 12i
Right child of i2i + 22i + 1
Sibling of ii + 1 if i is a left child (odd), i − 1 if right child (even)i + 1 if i is even, i − 1 if i is odd
Leavesindices ⌊n/2⌋ … n − 1⌊n/2⌋ + 1 … n

Worked Example: Build a Max Heap by Repeated Insertion

Insert 34, 45, 42, 56, 78, 4, 99, 32, 55, 90, 88 (each new key is added at the end and reheaped up):

InsertSwaps during reheap-upHeap array after insertion
34-34
4545↔3445 34
42-45 34 42
5656↔34, 56↔4556 45 42 34
7878↔45, 78↔5678 56 42 34 45
4-78 56 42 34 45 4
9999↔42, 99↔7899 56 78 34 45 4 42
32-99 56 78 34 45 4 42 32
5555↔3499 56 78 55 45 4 42 32 34
9090↔45, 90↔5699 90 78 55 56 4 42 32 34 45
8888↔5699 90 78 55 88 4 42 32 34 45 56
TEXT
                 99
            /          \
          90            78
        /    \         /  \
      55      88      4    42
     /  \    /  \
   32   34  45   56

Worked Example: Priority Queue of Tasks with a Min Heap

Tasks arrive with priorities (smaller number = more urgent): T1:4, T2:2, T3:6, T4:3, T5:1.

OperationMin-heap array (priorities)
insert T1(4)4
insert T2(2)2 4
insert T3(6)2 4 6
insert T4(3)2 3 6 4 (3 swapped with its parent 4)
insert T5(1)1 2 6 4 3 (1 moves up twice)
deleteMin → T52 3 6 4 (last key 3 to root, reheap down below 2)
deleteMin → T23 4 6
deleteMin → T44 6

Tasks are served in the order T5, T2, T4, T1, T3 - by priority, not by arrival.

🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Define Max-Heap and Min-Heap. Explain Reheap Up (Insertion) and Reheap Down (Deletion) with an example. (7.5 Marks)
  • Write: Completeness + Heap Order property, 0-based parent/child index formulas, reheapDown() C code, and worked insert/delete trace.
  • Q2. Explain how a Heap is used to implement a Priority Queue and state its time complexities. (5 Marks)
  • Write: O(log n) insert/extract, O(1) peek, O(n) bottom-up Build-Heap, and comparison with unsorted/sorted array &amp; linked list priority queues.