Download presentation
Presentation is loading. Please wait.
1
Priority Queues
2
Use of Heaps As we mentioned, heaps can be used in Heapsort
Priority Queues
3
Priority Queues A queue where we add objects, each with a value (“priority”). Priority queues are very common for job scheduling Two Types: Max-Priority Queue we use Max Heap Min-Priority Queue we use Min Heap
4
Operations on Priority Queues (Assume Max Queue)
Add a new object with priority K Return the object with the highest priority Remove the object with the highest priority Increase the priority of object O Heap data structure can implement all these operations efficiently
5
Remember If we need Max-Queue, we use Max Heap
If we need Min-Queue, we use Min Heap
6
1- Add New Object With Priority 9
Add the object to the heap Re-heapify if needed O (Log n) 14 12 9 8 10 14 12 5 8 10 5 9
7
2- Return the Highest-Priority Object
Return the root of the tree Same as: Return the first element in the Heap array In our example, return 14 O (1) 14 12 9 8 10 5
8
3- Remove the Highest-Priority Object
Remove the root of the tree Replace it with the lowest right-most object Re-heapify O (Log n) 14 12 9 8 10 5 5 12 9 8 10 12 5 9 8 10 12 10 9 8 5
9
4- Increase the Priority of Object O
Change 12 to 20 Change the value and re-heapify upwards O (Log n) 14 12 9 8 10 5 14 20 9 8 10 5 20 14 9 8 10 5
10
Summary of Heaps Very interesting data structure Common Usage
Balanced, left-justified binary trees Arrays Common Usage Heapsort always O(n log n) Priority queues most operations need O(log n) Two main types (depend on your application) MaxHeap: Parent value >= children values MinHeap: Parent value <= children values
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.