Heaps and Priority Queues Study Notes

Priority Queue Abstract Data Type (ADT)

  • A priority queue serves as a collection that stores items.

  • Each item within the priority queue is a pair consisting of a key and a value: (key,value)(key, value).

  • Main methods of the Priority Queue ADT include:

    • add(k,x)add(k, x): This method inserts an item with key kk and value xx into the collection.

    • remove_min()remove\_min(): This method removes and returns the specific item that has the smallest key within the collection.

  • Additional methods for management include:

    • len()len(): Returns the number of items stored.

    • is_empty()is\_empty(): Checks if the priority queue contains any items.

Heaps and Their Properties

  • A heap is a specialized binary tree designed to store keys at its nodes.

  • A heap must satisfy two primary properties:

    • Heap-Order Property: For every internal node vv (excluding the root node), the key of node vv must be greater than or equal to the key of its parent: key(v)≥key(parent(v))key(v) \geq key(parent(v)).

    • Complete Binary Tree Property: Let hh represent the height of the heap.

      • For every depth level i=0,…,h−1i = 0, \dots, h - 1, there must be exactly 2i2^i nodes present.

      • At the final depth level h−1h - 1, all internal nodes must be positioned to the left of the external nodes.

  • The Last Node: In a heap structure, the "last node" is defined as the rightmost node at the maximum depth of the tree.

Height of a Heap

  • Theorem: A heap that stores nn keys has a height of O(log⁡n)O(\log n).

  • This logarithmic relationship is demonstrated by the following examples:

    • O(log⁡8)=3O(\log 8) = 3

    • O(log⁡7)=2.8=2O(\log 7) = 2.8 = 2

    • O(log⁡16)=4O(\log 16) = 4

  • Structure of the levels:

    • Depth 00: 11 node.

    • Depth 11: 22 nodes.

    • Depth h−1h-1: 2h−12^{h-1} nodes.

    • The total number of keys scales with height such that height remains logarithmic relative to the number of nodes.

Implementation of Priority Queues using Heaps

  • Heaps are specialized structures with limited operations that effectively implement the Priority Queue ADT.

  • Every internal node in the heap stores a (key,element)(key, element) item.

  • The data structure keeps track of the position of the "last node" to facilitate efficient insertions and removals.

  • Types of Heaps:

    • Min-Heaps: The root contains the minimum key (e.g., items like (2,Sue)(2, \text{Sue}), (5,Pat)(5, \text{Pat}), (6,Mark)(6, \text{Mark}), (9,Jeff)(9, \text{Jeff}), (7,Anna)(7, \text{Anna})).

    • Max-Heaps: The root contains the maximum key.

Heap Insertion and the Upheap Algorithm

  • The insertion algorithm for adding a new key into a heap follows three distinct steps:

    1. Find the insertion node zz: This is the location that will become the new last node of the heap.

    2. Store the key: Place the new key kk at node zz.

    3. Restore Heap-Order: Execute the Upheap algorithm to ensure every child key remains greater than or equal to its parent key.

  • Upheap Algorithm (also known as sift-up, bubble-up, percolate-up, or heapify-up):

    • The heap-order property may be violated immediately after insertion.

    • The algorithm restores the property by swapping the new key kk upward along the path toward the root.

    • Termination conditions: The key kk reaches the root, or it reaches a node whose parent has a key smaller than or equal to kk.

    • Efficiency: Because the height of the heap is O(log⁡n)O(\log n), the upheap algorithm runs in O(log⁡n)O(\log n) time.

Max Heap Insertion Example

  • Consider a Max Heap where the rule is key(v)≤key(parent(v))key(v) \leq key(parent(v)).

  • Initial set of keys includes 100100, 8484, 7171 (at level 1), and 6060, 2323, 1212, 2929 (at level 2), with 11, 3737, 44 at level 3.

  • Process for inserting a new key 9090:

    1. Create a new node for 9090.

    2. Link the node as the last child (as the right child of the parent of nodes 11, 3737, and 44).

    3. Sift-up Step 1: Swap 2323 and 9090 because 90>2390 > 23.

    4. Sift-up Step 2: Swap 8484 and 9090 because 90>8490 > 84.

    5. The value 9090 stops because it is less than the root 100100.

Heap Removal and the Downheap Algorithm

  • The item with the smallest key is consistently located at the root of a min-heap.

  • Removals are restricted to the root node only.

  • The removal algorithm consists of three steps:

    1. Replacement: Replace the root key with the key of the current last node ww.

    2. Removal: Remove node ww from the heap (it is no longer the last node).

    3. Restore Heap-Order: Execute the Downheap algorithm to ensure all child keys are greater than or equal to their parent keys.

  • Downheap Algorithm (also known as sift-down):

    • The heap-order property is often violated after the root is replaced by a larger key from the bottom of the tree.

    • The algorithm restores order by swapping the key kk downward from the root.

    • Termination conditions: Key kk reaches a leaf node, or it reaches a node whose children all possess keys greater than or equal to kk.

    • Efficiency: Similar to upheap, downheap runs in O(log⁡n)O(\log n) time due to the tree's height.

Downheap Visual Example

  • Consider a removal operation on a heap containing items like (4,C)(4, C), (5,A)(5, A), (6,Z)(6, Z), (15,K)(15, K), (9,F)(9, F), (7,Q)(7, Q), (20,B)(20, B), and others.

  • When the root (4,C)(4, C) is removed, it is replaced by the last node (e.g., (13,W)(13, W)).

  • The Downheap process moves (13,W)(13, W) down the tree by comparing it against its children and swapping it with the smaller of the two children to maintain min-heap property.

Array-Based Heap Implementation

  • A heap with nn keys can be represented efficiently using an array of length nn.

  • Links between nodes are not explicitly stored as pointers.

  • Mapping nodes to indices:

    • The root is at index 00.

    • For a node at index ii, its left child is at index 2i+12i + 1 and its right child is at index 2i+22i + 2.

    • For a node at index ii, its parent is at index (i−1)/2(i - 1) / 2 (using integer division).

  • In the provided diagram, the nodes 2,5,6,9,72, 5, 6, 9, 7 map to array indices 0,1,2,3,40, 1, 2, 3, 4 respectively.

Comprehensive Trace Example: Insertion and Removal

  • Task: Insert keys 3,4,8,7,2,6,9,5,13, 4, 8, 7, 2, 6, 9, 5, 1 into an empty min-heap in order.

  • Step-by-Step Insertion:

    1. Insert 33: Root is 33.

    2. Insert 44: 44 is the left child of 33.

    3. Insert 88: 88 is the right child of 33.

    4. Insert 77: 77 is the left child of 44.

    5. Insert 22: 22 is placed as the right child of 44. Upheap: 22 is smaller than 44, so they swap. Now 22 is at the level below the root, and 44 is its child. Upheap: 22 is smaller than 33, so they swap. 22 is now the root.

    6. Insert 66: 66 is the left child of 88. Upheap: 66 is smaller than 88, so swap 66 and 88.

    7. Insert 99: 99 is the right child of 66 (which is the new position of 88's predecessor).

    8. Insert 55: 55 is the left child of 77. Upheap: 55 is smaller than 77, so swap 55 and 77.

    9. Insert 11: 11 is placed as the right child of 55. Upheap: 11 swaps with 55, then with 33, then with 22 to become the root.

  • Step-by-Step Removal (from end of insertion state):

    1. Identify the root to remove (key 22).

    2. The last node is replaced into the root position. If current last node is 77, move 77 to the root.

    3. Downheap: Compare root 77 with children 33 and 66. Swap 77 with the smallest child (33).

    4. Downheap: Compare 77 at its new position with its children 55 and 44. Swap 77 with the smaller child (44).

    5. The process continues until the heap-order property is fully satisfied.