Priority Queues (Heaps) : 1 1 1 1 1 1 CPT S 223. School of EECS, WSU
Priority Queues (Heaps) : 1 1 1 1 1 1 CPT S 223. School of EECS, WSU
Motivation
Queues are a standard mechanism for ordering tasks on a first-come, first-served basis However, some tasks may be more important or timely than others (higher priority) Priority queues
Store tasks using a partial ordering based on priority Ensure highest priority task at head of queue
Main operations
Finds the current minimum element (read: highest priority) in the queue, deletes it from the queue, and returns it
10
19
insert()
deleteMin()
2
Can we build a data structure better suited to store and retrieve priorities?
Simple Implementations
10
10
Ordered array
Balanced BST
Binary Heap
A priority queue data structure
Binary Heap
Structure Property
Each level (except possibly the bottom most level) is completely filled The bottom most level may be partially filled (from left to right)
Structure property
Array representation:
Heap-order Property
For every node X, key(parent(X)) key(X) Except root node, which has no parent Alternatively, for a MaxHeap, always keep the maximum key at the root
Duplicates are allowed No order implied for elements which do not share ancestor-descendant relationship
Cpt S 223. School of EECS, WSU 11
i 2i 2i + 1
i/2
Cpt S 223. School of EECS, WSU 12
Just finds the Min without deleting it insert deleteMin Note: a general delete() function is not as important for heaps but could be implemented
Heap Insert
Insert new element into the heap at the next available slot (hole)
Then, percolate the element up the heap while heap-order property not satisfied
Cpt S 223. School of EECS, WSU 14
Percolating Up
14 hole
15
Percolating Up
16
Percolating Up
(2) 14 vs. 21
14
17
Percolating Up
14 hole
(2) 14 vs. 21
14
(3) 14 vs. 13
Path of percolation up
18
19
20
Heap DeleteMin
Minimum element is always at the root Heap decreases by one in size Move last element into hole at root Percolate down while heap-order property not satisfied
21
Percolating down
22
Percolating down
23
Percolating down
31
24
Percolating down
31
31
Percolating down
25
Percolating down
31
Percolating down
26
Percolating down
31
decreaseKey(p,v)
increaseKey(p,v)
Lowers the current value of item p to new priority value v Need to percolate up E.g., promote a job
Increases the current value of item p to new priority value v Need to percolate down E.g., demote a job
Run-times for all three functions?
remove(p)
O(lg n)
30
What if all N elements are all available upfront? To build a heap with N elements:
Default method takes O(N lg N) time We will now see a new method called buildHeap() that will take O(N) time - i.e., optimal
31
Building a Heap
Perform N inserts O(N log2 N) worst-case Randomly populate initial heap with structure property Perform a percolate-down from each internal node (H[size/2] to H[1])
BuildHeap Example
Input: { 150, 80, 40, 10, 70, 110, 30, 120, 140, 60, 50, 130, 100, 20, 90 }
Leaves are all valid heaps (implicitly) Arbitrarily assign elements to heap nodes Structure property satisfied Heap order property violated Leaves are all valid heaps (implicit) So, let us look at each internal node, from bottom to top, and fix if necessary
33
BuildHeap Example
Nothing to do Swap with left child
Randomly initialized heap Structure property satisfied Heap order property violated Cpt (implicit) S 223. School of EECS, WSU Leaves are all valid heaps
34
BuildHeap Example
Nothing to do
BuildHeap Example
Nothing to do
BuildHeap Example
Swap path
BuildHeap Implementation
Run-time = ?
O(sum of the heights of all the internal nodes) because we may have to percolate all the way down to fix every internal node in the worst-case
HOW?
Theorem 6.1
For a perfect binary tree of height h, the sum of heights of all nodes is 2h+1 1 (h + 1)
Since h=lg N, then sum of heights is O(N) Will be slightly better in practice
Implication: Each insertion costs O(1) amortized time
Cpt S 223. School of EECS, WSU 39
40
buildHeap insert: O(N) for N inserts deleteMin: O(lg N) decreaseKey: O(lg N) increaseKey: O(lg N) remove: O(lg N)
Cpt S 223. School of EECS, WSU 41
Applications
Graph algorithms
Event simulation
Sort the list => O(n log n) Pick the kth element => O(1) Use a binary heap (minheap)
Cpt S 223. School of EECS, WSU 43
A better algorithm:
1. 2. 3.
Total run-time = O(n + k log n) If k = O(n/log n) then the run-time becomes O(n)
44
Leftist Heaps
Skew Heaps
Fibonacci Heaps
Cpt S 223. School of EECS, WSU 45
DeleteMin
O(log n)
Merge (=H1+H2)
O(n)
Leftist Heap
Skew Heap Binomial Heap
O(log n)
O(log n) O(log n) worst case O(1) amortized for sequence of n inserts
O(log n)
O(log n) O(log n)
O(log n)
O(log n) O(log n)
Fibonacci Heap
O(1)
O(log n)
Cpt S 223. School of EECS, WSU
O(1)
46
#include <priority_queue> int main () { priority_queue<int> Q; Q.push (10); cout << Q.top (); Q.pop (); } Calls DeleteMax()
For MinHeap: declare priority_queue as: priority_queue<int, vector<int>, greater<int>> Q; Refer to Book Chapter 6, Fig 6.57 for an example
Cpt S 223. School of EECS, WSU 47
Binomial Heaps
48
Binomial Heap
Its structure property is totally different Its heap-order property (within each binomial tree) is the same as in a binary heap
Cpt S 223. School of EECS, WSU
49
Depth:
B3:
#nodes:
3 (0 ) 3 (1 ) 3 (2 ) 3 (3 )
50
We know that:
i) A binomial heap should be a forest of binomial trees ii) Each binomial tree has power of 2 elements
n = 31 = (1 1 1 1 1)2
51
n = 31 = (1 1 1 1 1)2
Forest of binomial trees {B0, B1, B2, B3, B4 }
Bi == Bi-1 + Bi-1
B0
B1 B3 B2
52
Lemma: There exists a binomial heap for every positive value of n Proof:
Have one binomial tree for each power of two with co-efficient of 1 Eg., n=10 ==> (1010)2 ==> forest contains {B3, B1}
53
Property
Each binomial tree should contain the minimum element at the root of every subtree
Just like binary heap, except that the tree here is a binomial tree structure (and not a complete binary tree)
55
56
Key Properties
What is the upper bound on the number of binomial trees in a binomial heap of n nodes? lg n
B7
B6
B5
B4
B3
B2
B1
B0
59
DeleteMin()
Goal: Given a binomial heap, H, find the minimum and delete it Observation: The root of each binomial tree in H contains its minimum element Approach: Therefore, return the minimum of all the roots (minimums) Complexity: O(log n) comparisons (because there are only O(log n) trees)
Cpt S 223. School of EECS, WSU 60
For DeleteMin(): After delete, how to adjust the heap? New Heap : Merge { B0, B2 } & { B0, B1, B2 }
Cpt S 223. School of EECS, WSU 61
So, if we decide how to do merge we will automatically figure out how to implement both insert() and deleteMin()
Cpt S 223. School of EECS, WSU 62
Merge(H1,H2)
Let n1 be the number of nodes in H1 Let n2 be the number of nodes in H2 Therefore, the new heap is going to have n1 + n2 nodes
Assume n = n1 + n2
Logic:
Merge trees of same height, starting from lowest height trees If only one tree of a given height, then just copy that Otherwise, need to do carryover (just like adding two binary numbers)
Cpt S 223. School of EECS, WSU 63
Merge: Example
B0
13
B1
B2
64
Note: Merge is defined for only binomial trees of with the same height Cpt S 223. School EECS, WSU
65
Merge(H1,H2) example
carryover
13
14 26 16 26
66
How to Merge more than two binomial trees of the same height?
Merging more than 2 binomial trees of the same height could generate carryovers
+
14
+
26
16 26
Input: +
Merge(H1,H2) : Example
Output:
There are two other possible answers Merge cost log(max{n1,n2}) = O(log n) comparisons
Cpt S 223. School of EECS, WSU 68
Run-time Complexities
It can be further proved that an uninterrupted sequence of m Insert operations takes only O(m) time per operation, implying O(1) amortize time per insert
Proof Hint:
unaffected affected
10010111 1 -------------10011000
For each insertion, if i is the least significant bit position with a 0, then number of comparisons required to do the next insert is i+1 If you count the #bit flips for each insert, going from insert of the first element to the insert of the last (nth) element, then => amortized run-time of O(1) per insert
Cpt S 223. School of EECS, WSU 69
Insert
O(lg n) worst-case O(1) amortized time if insertion is done in an uninterrupted sequence (i.e., without being intervened by deleteMins) O(lg n) worst-case
DeleteMin, FindMin
Merge
O(lg n) worst-case
70
DeleteMin
O(log n)
Merge (=H1+H2)
O(n)
Leftist Heap
Skew Heap Binomial Heap
O(log n)
O(log n) O(log n) worst case O(1) amortized for sequence of n inserts
O(log n)
O(log n) O(log n)
O(log n)
O(log n) O(log n)
Fibonacci Heap
O(1)
O(log n)
Cpt S 223. School of EECS, WSU
O(1)
71
Summary
Priority queues maintain the minimum or maximum element of a set Support O(log N) operations worst-case
72