Computer Science 2 Heaps
Learning Objectives Understand the properties of a heap Understand how to add to a heap Understand how to remove from a heap
Uses for Heaps Priority Queue. Efficient way of having the first element on the top of the heap. Heapsort: O(N log N) Better worst case scenario than using a Tree to sort
Properties of a Heap Full Tree Parents are greater than their children.
Heaps: Examples Are heaps BSTs ?? wrong! 24 7 3 30 10 40 80 25 48 21 14 17 33 9 18 28 11 22 35 50 20 wrong! Are heaps BSTs ??
Inserting a node Increase the size by 1 Add it to the bottom of the heap Reheap up. While the child is greater than its parents Switch them
Heaps: Insertion example Adding a new node with key = 8 at the “end” of this heap violates the order property. New node has larger key than its parent, swap nodes to fix this. 16 5 11 3 8 Is the order property restored? Is 3 < 8? Yes. Is 8 < 16? Yes. Is this a coincidence? 16 8 11 3 5
Heaps: Insertion example If the new node had had key = 18, what would have happened? 16 5 11 3 18 Swap with the parent. Is the order property restored? Is 3 < 18? Yes. Is 18 < 16? No. 16 18 11 3 5
Heaps: Insertion example Swap again: order property restored. 18 16 11 3 5 In general, we “bubble up” the new node until the order property is restored.
Your Turn Create a heap by adding the following values 20, 10, 30, 15 Add the following to the heap 40, 18, 32
Removing from a Heap Take off the top Move the bottom to the top Decrease the size of the heap Reheap Down If the top < greatest child Switch top and greatest child Continue until the parent is not < it’s greatest child.
Heaps: Removing largest key The largest key is at the top. Remove it. Move “last” node to the top, to maintain shape. ‘Re-heap down’ until the order property is restored. 18 16 11 16 11 3 5 3 5
Heaps: Removing largest key 5 16 16 11 5 11 3 3 Did we have to reheap down the left? Why?
Removal: another example y p r d f a c k b c p r d f a k b r p c d f a k b r p k d f a c b
Your Turn Using the heap created previously Show what it looks like after removing one item.
Implementing it into an array: Adding How do you find the parents of a child? … ChildPosition / 2 Adding to a heap Increase the size by 1 Add it to the bottom of the heap Reheap up. While the child is greater than its parent Switch them Size 8 r p k d f a c b Dry run. Add a z and a q to the heap. 1 2 3 4 5 6 7 8 9 10 R P K D F C B A
Implementing it into an array: Removing How do you find the children? … parentPosition*2 and parentPosition*2 +1 Size 8 Removing Take off the top Move the bottom value to the top Decrease the size of the heap Reheap Down While there are children and added < greatest child Switch added and greatest child r p k d f a c b 1 2 3 4 5 6 7 8 9 10 R P K D F C B A
Heaps of Fun Program Menu Push: Add Show All Show and remove the top of the heap. Push: Implement a heap sort Switch top and bottom Rehead down, excluding the last element(s)