Presentation is loading. Please wait.

Presentation is loading. Please wait.

Definition Applications Implementations Heap Comparison

Similar presentations


Presentation on theme: "Definition Applications Implementations Heap Comparison"— Presentation transcript:

1 Definition Applications Implementations Heap Comparison
Priority Queues Definition Applications Implementations Heap Comparison 4/6/2019 CS 303 – Priority Queues Lecture 12

2 Priority Queues Specialization of SET Operations
Insert(x,A) A  A U {x} DeleteMin(A,x) x  Min(A) MakeNull(A) A  A – {Min(A)} cf: QUEUE – difference is that Insert can occur anywhere 4/6/2019 CS 303 – Priority Queues Lecture 12

3 Priority Queue Applications
Scheduling Simulation Other “event driven” applications move clock to next event and execute – DeleteMin spawn new event in the future – Insert Sorting(!) A  NULL for i  1 to n do Insert(x[i],A) for i  1 to n do DeleteMin(A,x[i]) 4/6/2019 CS 303 – Priority Queues Lecture 12

4 Priority Queue Implementations
Unsorted List Sorted List Insert: easy O(1) Insert: hard O(n/2) DeleteMin: hard O(n/2) DeleteMin: easy O(1) Unsorted Array Sorted Array Insert: easy O(1) Insert: hard O(log n + n/2) DeleteMin: hard O(n/2) DeleteMin: easy O(1) [how?] Why keep the entire list sorted, just to find min? Partial Order is a better idea! a a < b a < c b ? c b c 4/6/2019 CS 303 – Priority Queues Lecture 12

5 Heap Partially Ordered Binary Tree HeapShape Balanced
Missing nodes are at leaf level and to the far right DeleteMin x  a Need to replace root 1) find rightmost leaf = r 2) swap r with the hole at the root 3) push r down until r < b, r < c a O b c b c r b c if (b<c) & (r<b) SWAP(r,b) and continue down... 4/6/2019 CS 303 – Priority Queues Lecture 12

6 Heap ... Insert into Heap 1) add x as the new rightmost leaf
2) push x UP until p < x (or x == root) Q/ do you need to push p down? A/ no! Why? Because p was already smaller than everything in both subtrees below p. When it becomes the root of one subtree, it is still smaller than both children x p s x if (x < p) SWAP(x,p) and continue up... 4/6/2019 CS 303 – Priority Queues Lecture 12

7 Array Implementation of Heap (a classic hack!)
1 a b c d e f g h i j a c b d e f g h i j RightMostLeaf No pointers (they are implicit) Easy to find/create/remove RightMostLeaf Insert & Delete are O(log n) (but Member is O(n), so beware) 4/6/2019 CS 303 – Priority Queues Lecture 12

8 Implementation Comparison Chart
Binary Search Tree Hash Table Heap (average case only!) Insert O(log n) O(n/b) O(log n) Delete O(log n) O(n/b) [ O(n) ] DeleteMin O(log n) O(n) O(log n) Member O(log n) O(n/b) [ O(n) ] Don’t use Heap if you need Delete or Member! Don’t use Hash Table if you need DeleteMin! If you use a BST – beware of worst-case behavior! 4/6/2019 CS 303 – Priority Queues Lecture 12


Download ppt "Definition Applications Implementations Heap Comparison"

Similar presentations


Ads by Google