Heaps Section 6.4, Pg. 309 (Section 9.1)
Motivation: Prim’s Algorithm Starting node T How many times is this edge visited? 3 times Problem: You keep comparing the same edges over and over. Solution: Use priority queues containing the edges
Priority Queues Typical example: printing in a Unix/Linux environment. Printing jobs have different priorities. These priorities override the FIFO policy of the queues Operations supported in a priority queue: Insert a new element Extract/Delete of the element with the highest priority The priority is a number
Implementing Priority Queues: min-HEAPS We assume that each element has a key, K, and other information, I. K is the priority of I. Heap greater A min-Heap is a binary tree T such that: The priority of the element in any node is less or equal than the priority of the elements in its children nodes T is complete Note: The algorithms for Heaps are the same as for min-Heaps. Just invert the comparisons.
(non) Examples 10 > 9! Tree is not complete 5 5 5 8 8 8 10 9 9 16 12 9 56 12 16 10 12
Insert a New Element Idea: insert the new element as the last leaf and re-adjust the tree 5 8 9 16 12 18 20 22 44 10 13 56 Insert 7
Insert a New Element (II) Step 1: add it as the last leaf 5 8 9 16 12 18 20 22 44 10 13 56 7
Insert a New Element (III) Steps 2, 3 ,… : swap until key is in the right place 5 8 9 12 56 16 7 22 44 13 10 18 20
Insert a New Element (IV) Steps 2, 3 ,… : swap until it finds its place 5 8 7 12 56 16 9 22 44 13 10 18 20 Complexity is O(log2 n)
Extract/Delete the Element with the Lowest Priority Idea: the root has always the lowest priority. Then delete it and replace it with the last child. Re-adjust the tree. 5 8 9 16 12 18 20 22 44 10 13 56 Extract/Step 1: returns 5
Extract/Delete the Element with the Lowest Priority (II) Step 2: Put the last key as the new root. 13 8 9 12 56 16 10 22 44 18 20
Extract/Delete the Element with the Lowest Priority (III) Steps 3, 4, … : Swap until key is in the correct place. Always swap with node that has the lowest priority. 8 13 9 12 56 16 10 22 44 18 20
Extract/Delete the Element with the Lowest Priority (IV) Steps 3, 4, … : Swap until key is in the correct place. Always swap with node that has the lowest priority. 8 12 9 13 56 16 10 22 44 18 20 Complexity is O(log2 n)
Complete Trees can be Represented in Arrays 5 8 9 16 12 18 20 22 44 10 13 56 0 1 2 … Corresponding array: 5 8 9 16 12 10 56 18 20 22 44 13
Operations in Array Representation of Complete Trees Assume that the first index in the array is 0 and that the number of keys is n root(i): i = 0 LeftChild(i): 2i + 1 rightChild(i): 2i + 2 isLeaf(i): Homework Parent(i): Homework
Using Priority Queues in Prim’s Algorithm The Fringe (neighbors of T) are maintained in a priority list (min-Heap), which ensures O((|E|+|V|)log2|E|) Maintaining the Fringe is the crucial aspect of Djisktra’s Algorithm for computing shortest path between two points (next class)