Download presentation
Presentation is loading. Please wait.
1
Heaps
2
Who's First? Priority Queue : Items coming in in random order
Want to process them in some order of priority
3
Who's First Approaches Unsorted list Sorted list BST
O(1) insert, O(n) Find next, O(n) remove next Sorted list O(n) insert, O(1) Find next, O(1) remove next BST O(logn) insert, O(logn) Find next, O(logn) remove next
4
Binary Heaps Binary Heap :
Heap Property : tree where each node is <= children (min heap) or >= than children (max heap)
5
Simplified Alternative
Binary Heap : Built as complete binary tree Every level but last is full, last is filled left to right
6
Heap vs BST Heap BST Complete – Guaranteed logn height
May have gaps – Could be n Smallest item at top Smallest item farthest to left No guaranteed order between siblings Strict ordering
7
Simplified Can represent in an array without gaps
8
Navigation Parent Index = Left Child Index = Right Child Index =
9
Navigation Parent Index = floor((Index-1)/2) Left Child Index =
Right Child Index =
10
Navigation Parent Index = floor((Index-1)/2)
Left Child Index = Index * 2 + 1 Right Child Index = Index * 2 + 2
11
Alternative Can skip index 0 to simplify array math:
Parent = index / 2 left = index * 2, right = index * 2 + 1
12
Add To Heap Always add to next slot 1 2 3 4 5 6 7 8 9 10 11 14 18 19
1 2 3 4 5 6 7 8 9 10 11 14 18 19 21 33 17 27
13
Add To Heap Always add to next slot Float to restore heap 1 2 3 4 5 6
1 2 3 4 5 6 7 8 9 10 11 14 19 21 33 17 27 18
14
Add To Heap Always add to next slot Float to restore heap 1 2 3 4 5 6
1 2 3 4 5 6 7 8 9 10 11 14 19 21 33 17 27 18
15
Add To Heap Always add to next slot Float to restore heap 1 2 3 4 5 6
1 2 3 4 5 6 7 8 9 10 11 14 19 21 33 17 27 18
16
Remove Min Only remove from root Size = 10 1 2 3 4 5 6 7 8 9 10 11 14
1 2 3 4 5 6 7 8 9 10 11 14 18 19 21 33 17 27
17
Remove Min Only remove from root Replace with last item in array
Size = 9 1 2 3 4 5 6 7 8 9 10 27 11 14 18 19 21 33 17
18
Remove Min Swap down to restore heap Always pick smallest child
Size = 9 1 2 3 4 5 6 7 8 9 10 27 11 14 18 19 21 33 17
19
Remove Min Swap down to restore heap Always pick smallest child
Size = 9 1 2 3 4 5 6 7 8 9 10 14 11 27 18 19 21 33 17
20
Remove Min Swap down to restore heap Always pick smallest child
Size = 9 1 2 3 4 5 6 7 8 9 10 14 11 17 18 19 21 33 27
21
Remove Min Stop if both children are larger 18 Size = 8 1 2 3 4 5 6 7
1 2 3 4 5 6 7 8 9 10 14 18 17 19 21 33
22
Remove Min Watch for just left child Size = 8 1 2 3 4 5 6 7 8 9 10 14
1 2 3 4 5 6 7 8 9 10 14 11 17 18 19 21 33
23
Heap BigO BigO's for heap Find Next : O(1) Insert : O(logn)
Remove Min : O(logn)
24
Std::priority_queue Basis of std::priority_queue priority_queue
25
Heap Class Array based Capacity = array size heapSize = num items
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.