Download presentation
Presentation is loading. Please wait.
1
CS 2511 Fall 2014 Binary Heaps
2
Disadvantage of Linear Priority Queues
Two Basic Types of Implementation: Array Both adding and removing takes O(n) time due to data movements Linked List Adding takes O(n) time due to searching
3
Representing a Heap 2 3 4 8 7 9 14 16 10 1 2 3 4 5 6 7 8 9 10 11 12 Array Index 2 4 3 8 7 9 14 16 10 Array Value
4
Adding to a Heap (Step 1) 2 Want to add 1 3 4 8 7 9 14 16 10 1 1 2 3 4
1 2 3 4 5 6 7 8 9 10 11 12 Array Index 2 4 3 8 7 9 14 16 10 1 Array Value
5
Adding to a Heap (Step 2) 2 Want to add 1 3 4 8 1 9 14 16 10 7 1 2 3 4
1 2 3 4 5 6 7 8 9 10 11 12 Array Index 2 4 3 8 1 9 14 16 10 7 Array Value
6
Adding to a Heap (Step 3) 2 Want to add 1 3 1 8 4 9 14 16 10 7 1 2 3 4
1 2 3 4 5 6 7 8 9 10 11 12 Array Index 2 1 3 8 4 9 14 16 10 7 Array Value
7
Adding to a Heap (Step 4) 1 Want to add 1 3 2 8 4 9 14 16 10 7 1 2 3 4
1 2 3 4 5 6 7 8 9 10 11 12 Array Index 1 2 3 8 4 9 14 16 10 7 Array Value
8
Removing from a Heap (Step 1)
7 1 Want to remove 1 3 2 8 4 9 14 16 10 7 1 2 3 4 5 6 7 8 9 10 11 12 Array Index 7 1 2 3 8 4 9 14 16 10 7 Array Value
9
Removing from a Heap (Step 2)
Want to remove 1 3 7 8 4 9 14 16 10 1 2 3 4 5 6 7 8 9 10 11 12 Array Index 2 7 3 8 4 9 14 16 10 Array Value
10
Removing from a Heap (Step 3)
2 Want to remove 1 3 4 8 7 9 14 16 10 1 2 3 4 5 6 7 8 9 10 11 12 Array Index 2 4 3 8 7 9 14 16 10 Array Value
11
Relationship between Maximum Size and Height
Height (h) Maximum Size (n) 1 3 2 7 15 4 31 … h 2h+1-1
12
Efficiency of Binary Heaps
Number of Operations for Add or Remove limited by its height Maximum height is log2(n+1) – 1, where n is the number of nodes O(log(n)) n = 2h + 1 − 1 n + 1 = 2h + 1 log2(n + 1) = log2(2h + 1) log2(n + 1) = (h + 1) * log2(2) log2(n + 1) = (h + 1) * 1 log2(n + 1) = h + 1 h = log2(n + 1) – 1 Reminder: log2(n + 1) = log(n+1) / log(2) True height is ceil(log2(n + 1) – 1)
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.