Presentation is loading. Please wait.

Presentation is loading. Please wait.

Priority Queues and Binary Heaps Fundamental Data Structures and Algorithms Peter Lee February 4, 2003.

Similar presentations


Presentation on theme: "Priority Queues and Binary Heaps Fundamental Data Structures and Algorithms Peter Lee February 4, 2003."— Presentation transcript:

1 Priority Queues and Binary Heaps 15-211 Fundamental Data Structures and Algorithms Peter Lee February 4, 2003

2 Announcements HW3 is available  due Monday, Feb.10, 11:59pm  start today! Quiz #1 available Thursday  an online quiz  requires up to one hour of uninterrupted time with a web browser  must be completed by Friday, 11:59pm HW4 in teams of two  go to recitation for details

3 Priority Queues

4 Priority queues Today we consider a useful abstract data type called the priority queue.

5 Priority queue ADT Assume we have objects x that can be compared using the < and == operators.  These are Comparable objects. insert(k, o)  Inserts comparable object k into the priority queue with object o. deleteMin()  Returns and removes the minimum element from the priority queue.

6 The priority queue interface create insert void insert (Comparable key, Object r) findMin Comparable findMin () deleteMin Comparable deleteMin ()

7 Priority Queues: Applications Event simulations (key is time) Shortest paths in a graph Huffman codes Sorting

8 Linked list  deleteMinO(1)O(N)  insert O(N)O(1) Search trees  All operationsO(log N) Heaps avg (assume random)worst  deleteMinO(log N) O(log N)  insert2.6O(log N) special case :  buildheapO(N)O(N) i.e., insert*N or Possible priority queue implementations

9 Linked list  deleteMinO(1)O(N)  insert O(N)O(1) Search trees  All operationsO(log N) Heaps avg (assume random)worst  deleteMinO(log N) O(log N)  insert2.6O(log N) special case :  buildheapO(N)O(N) i.e., insert*N or Possible priority queue implementations

10 Linked list  deleteMinO(1)O(N)  insert O(N)O(1) Search trees  All operationsO(log N) Heaps avg (assume random)worst  deleteMinO(log N) O(log N)  insert2.6O(log N) special case :  buildheapO(N)O(N) i.e., insert*N or Possible priority queue implementations

11 A Digression: Perfect and Complete Binary Trees

12 Perfect binary trees 13 266532 16 2665266526 6819 21 3124

13 Perfect binary trees 13 266532 16 2665266526 6819 21 3124 26652665266526652665266526652665

14 Perfect binary trees 13 266532 16 2665266526 6819 21 3124 266526652665266526652665266526652665266526652665266526652665266526652665266526652665266526652665

15 Perfect binary trees How many nodes? 13 2665 24 32 16 2665266526 6819 21 31

16 Perfect binary trees How many nodes?  N = 2 4 - 1 = 15 13 2665 24 32 16 2665266526 6819 21 31 h=3h=3 N=15

17 Perfect binary trees How many nodes?  N = 2 4 - 1 = 15   Most of the nodes are ______ 13 2665 24 32 16 2665266526 6819 21 31 h=3h=3 N=15

18 Perfect binary trees How many nodes?  N = 2 4 - 1 = 15   Most of the nodes are leaves 13 2665 24 32 16 2665266526 6819 21 31 h=3 How many edges? h=3 N=15

19 Perfect binary trees How many nodes?  N = 2 4 - 1 = 15  In general: N =  Most of the nodes are leaves 13 2665 24 32 16 2665266526 6819 21 31 h=3h=3 N=15

20 Perfect binary trees How many nodes?  N = 2 4 - 1 = 15  In general: N = = 2 h+1 - 1  Most of the nodes are leaves 13 2665 24 32 16 2665266526 6819 21 31 h=3h=3 N=15

21 Quiz Break

22 Red-green quiz In a perfect binary tree, what is the sum of the heights of the nodes?  Give a mathematical characterization.  Give a tight upper bound (in big-O terms)

23 Perfect binary trees What is the sum of the heights? S = < N = O(N) 13 2665 24 32 16 2665266526 6819 21 31 h=3 N=15

24 Complete binary trees 21 13 2665 24 32 316819 16

25 Complete binary trees 2 1 98 4 10 576 3

26 Representing complete binary trees Linked structures? 2 1 98 4 10 576 3

27 Representing complete binary trees Linked structures? No! Instead, use arrays! 2 1 98 4 10 576 3

28 Representing complete binary trees Arrays  Parent at position i in the array  Children at positions 2i and 2i+1 2 1 98 4 10 576 3

29 Representing complete binary trees Arrays ( 1-based )  Parent at position i  Children at 2i and 2i+1. 2 1 98 4 10 576 3 1 2 3 4 5 6 7 8 9 10

30 Representing complete binary trees Arrays ( 1-based )  Parent at position i  Children at 2i and 2i+1. 2 1 98 4 10 576 3 1 2 3 4 5 6 7 8 9 10

31 Representing complete binary trees Arrays ( 1-based )  Parent at position i  Children at 2i (and 2i+1). 2 1 98 4 10 576 3 1 2 3 4 5 6 7 8 9 10

32 Representing complete binary trees Arrays ( 1-based )  Parent at position i  Children at 2i and 2i+1. public class BinaryHeap { private Comparable[] heap; private int size; public BinaryHeap(int capacity) { size=0; heap = new Comparable[capacity+1]; }...

33 Representing complete binary trees Arrays  Parent at position i  Children at 2i and 2i+1. Example: find the leftmost child int left=1; for(; left<size; left*=2); return heap[left/2]; Example: find the rightmost child int right=1; for(; right<size; right=right*2+1); return heap[(right-1)/2];

34 Back to Our Main Topic: Implementing Priority Queues with Binary Heaps

35 Binary heaps: the invariant Representation invariants 1. Structure property Complete binary tree (i.e. the elements of the heap are stored in positions 1…size of the array) 2. Heap order property Parent keys less than children keys

36 Heaps Representation invariant 1. Structure property Complete binary tree Hence: efficient compact representation 2. Heap order property Parent keys less than children keys Hence: rapid insert, findMin, and deleteMin O(log(N)) for insert and deleteMin O(1) for findMin

37 The heap order property Each parent is less than each of its children. Hence: Root is less than every other node.  (obvious proof by induction) 13 2665 24 32 316819 1621

38 Operating with heaps Representation invariant: All methods must: 1. Produce complete binary trees 2. Guarantee the heap order property All methods may assume 1. The tree is initially complete binary 2. The heap order property holds

39 Constructor method All methods must: 1. Produce complete binary trees Trivially true 2. Guarantee the heap order property Also trivially true This is the base case

40 findMin () The code public boolean isEmpty() { return size == 0; } public Comparable findMin() { if(isEmpty()) return null; return heap[1]; } Does not change the tree  Trivially preserves the invariant

41 insert (Comparable x) Process 1. Create a “hole” at the next tree cell for x. heap[size+1] This preserves the completeness of the tree. 2. Percolate the hole up the tree until the heap order property is satisfied. This assures the heap order property is satisfied.

42 insert (Comparable x) Process 1. Create a “hole” at the next tree cell for x. heap[size+1] This preserves the completeness of the tree assuming it was complete to begin with. 2. Percolate the hole up the tree until the heap order property is satisfied. This assures the heap order property is satisfied assuming it held at the outset.

43 Percolation up public void insert(Comparable x) throws Overflow { if(isFull()) throw new Overflow(); int hole = ++size; for(; hole>1 && x.compareTo(heap[hole/2])<0; hole/=2) heap[hole] = heap[hole/2]; heap[hole] = x; }

44 Percolation up Bubble the hole up the tree until the heap order property is satisfied. hole = 11 HOP false 13 2665 24 32 316819 16 14 Not really there... 21

45 Percolation up Bubble the hole up the tree until the heap order property is satisfied. hole = 11hole = 5 HOP falseHOP false 13 2665 24 32 316819 16 14 13 2665 24 32 146819 16 31 21

46 Percolation up Bubble the hole up the tree until the heap order property is satisfied. hole = 5hole = 2 HOP falseHOP true done 13 2665 24 32 216819 16 31 13 2665 24 32 146819 16 31 1421

47 Percolation up public void insert(Comparable x) throws Overflow { if(isFull()) throw new Overflow(); int hole = ++size; for(; hole>1 && x.compareTo(heap[hole/2])<0; hole/=2) heap[hole] = heap[hole/2]; heap[hole] = x; } Integer division

48 deleteMin() /** * Remove the smallest item from the priority queue. * @return the smallest item, or null, if empty. */ public Comparable deleteMin( ) { if(isEmpty()) return null; Comparable min = heap[1]; heap[1] = heap[size--]; percolateDown(1); return min; } Temporarily place last element at top Grab min element !!!

49 Percolation down Bubble the transplanted leaf value down the tree until the heap order property is satisfied. 14 31 2665 24 32 216819 16 14 -- 2665 24 32 216819 16 31 12

50 Percolation down Bubble the transplanted leaf value down the tree until the heap order property is satisfied. 31 14 2665 24 32 216819 1614 31 2665 24 32 216819 16 23

51 Percolation down Bubble the transplanted leaf value down the tree until the heap order property is satisfied. 21 14 2665 24 32 316819 1631 14 2665 24 32 216819 16 34done

52 percolateDown(int hole) private void percolateDown( int hole ) { int child = hole; Comparable tmp = heap[hole]; for( ; hole*2 <= size; hole=child ) { child = hole * 2; if(child!=size && heap[child+1].compareTo(heap[child]) < 0) child++; if(array[child].compareTo(tmp) < 0) heap[hole] = heap[child]; else break; } heap[hole] = tmp; } Is there a right child? Bubble up if smaller than tmp Initially 1 Select smaller child Finally, place the orphan Start at left child Exit loop if not bubbling

53 deleteMin () Observe that both components of the representation invariant are preserved by deleteMin. 1. Completeness The last cell ( heap[size] ) is vacated, providing the value to percolate down. This assures that the tree remains complete. 2. Heap order property

54 deleteMin () Observe that both components of the representation invariant are preserved by deleteMin. 1. Completeness The last cell ( heap[size] ) is vacated, providing the value to percolate down. This assures that the tree remains complete. 2. Heap order property

55 deleteMin () Observe that both components of the representation invariant are preserved by deleteMin. 1. Completeness The last cell ( heap[size] ) is vacated, providing the value to percolate down. This assures that the tree remains complete. 2. Heap order property The percolation algorithm assures that the orphaned value is relocated to a suitable position.

56 buildHeap() Start with complete (unordered) tree Starting from bottom, repeatedly call percolateDown() Void buildHeap () { for (int i = size/2; i>0; i--) percolateDown(i); }

57 buildHeap() performance At each iteration, have to do work proportional to the height of the current node Therefore, total running time is bounded by the sum of the heights of all of the nodes

58 Another Digression: Invariants

59 Representation Invariants Necessary for a clear understand an algorithm or piece of code. The most useful kind of comment you can make in a piece of code!

60 (Invariants) Plus ça change, plus c’est la même chose The role of an induction hypothesis

61 (Invariants and induction) Induction hypothesis  What you are allowed to assume At the start About the result values of a recursive call About the object state when a method is called  What you must deliver At the end Of the result values when the recursive call returns About the object state when the method returns

62 (Invariants and induction) Induction hypothesis  What you are allowed to assume At the start of a loop iteration About the result values of a recursive call About the object state when a method is called  What you must deliver At the end of the loop iteration Of the result values when the recursive call returns About the object state when the method returns

63 (Invariants and induction) Induction hypothesis  What you are allowed to assume About the result values of a recursive call About the object state when a method is called  What you must deliver Of the result values when the recursive call returns About the object state when the method returns

64 (Invariants and induction) Induction hypothesis  What you are allowed to assume At the start of a loop iteration About the result values of a recursive call About the object state when a method is called  What you must deliver At the end of the loop iteration Of the result values when the recursive call returns About the object state when the method returns

65 (Invariants and induction) Induction hypothesis  What you are allowed to assume At the start of a loop iteration About the result values of a recursive call About the object state when a method is called  What you must deliver At the end of the loop iteration Of the result values when the recursive call returns About the object state when the method returns

66 (Invariants) Plus ça change, plus c’est la même chose The role of an induction hypothesis Invariants in programs  Loop invariants  Recursion invariants  Representation invariants

67 (Representation invariant) What must always be true of the data structure when an operation completes. Theorem :  Suppose each constructor assures the representation invariant is initially correct.  Suppose each method preserves the representation invariant, assuming it is true initially.  Then the representation invariant will always be true at the completion of each method.

68 (Representation invariant) What must always be true of the data structure when an operation completes. Theorem :  Suppose each constructor assures the representation invariant is initially correct.  Suppose each method preserves the representation invariant, assuming it is true initially.  Then the representation invariant will always be true at the completion of each method.

69 (Representation invariants) What must always be true of the data structure when an operation completes. Theorem:  Suppose each constructor assures the representation invariant is initially correct.  Suppose each method preserves the representation invariant, assuming it is true initially.  Then the representation invariant will always be true at the completion of each method.  Assuming the code is not concurrent!

70 Heapsort Obviously we can use a priority queue to sort... just insert all the keys then do repeated deleteMins However we can take advantage of the fact that the heap always uses the first part of the array to do this with no extra space. This is called heapsort.

71 Heapsort Reverse the sense of the heap order (largest at the root) Start from position 0 in the array (children are 2i+1 and 2i+2) Call it percDown(a, i, len) Public static void heapsort(Comparable[] a) { for(int i = a.length/2; i>=0; i--) percDown(a, i, a.length); for (int j = a.length-1; j>0; j--) { swapReferences(a, 0, j); percDown(a, 0, j); }

72 Heapsort invariant At the start of the loop over j:  a[j]…a[a.length-1] are sorted  a[0]…a[j-1] are a heap


Download ppt "Priority Queues and Binary Heaps Fundamental Data Structures and Algorithms Peter Lee February 4, 2003."

Similar presentations


Ads by Google