Priority Queues Two kinds of priority queues:
Min priority queue.
Max priority queue.
Min Priority Queue Collection of elements.
Each element has a priority or key.
Supports following operations:
isEmpty
size
add/put an element into the priority queue
get element with min priority
remove element with min priority
Max Priority Queue Collection of elements.
Each element has a priority or key.
Supports following operations:
isEmpty
size
add/put an element into the priority queue
get element with max priority
remove element with max priority
Complexity Of Operations Two good implementations are heaps and leftist trees.
isEmpty, size, and get => O(1) time
put and remove => O(log n) time where n is the size of the priority queue
Applications Sorting
use element key as priority
put elements to be sorted into a priority queue
extract elements in priority order
if a min priority queue is used, elements are extracted in ascending order of priority (or key)
if a max priority queue is used, elements are extracted in descending order of priority (or key)
Sorting Example Sort five elements whose keys are 6, 8, 2, 4, 1 using a max priority queue.
Put the five elements into a max priority queue.
Do five remove max operations placing removed elements into the sorted array from right to left.
After Putting Into Max Priority Queue Sorted Array
6 8 2 4 1 Max Priority Queue
After First Remove Max Operation Sorted Array
6 2 4 1 8 Max Priority Queue
After Second Remove Max Operation Sorted Array
2 4 1 8 6 Max Priority Queue
After Third Remove Max Operation Sorted Array
2 1 8 6 4 Max Priority Queue
After Fourth Remove Max Operation Sorted Array
1 8 6 4 2 Max Priority Queue
After Fifth Remove Max Operation Sorted Array
8 6 4 2 1 Max Priority Queue
Complexity Of Sorting Sort n elements.
n put operations => O(n log n) time.
n remove max operations => O(n log n) time.
total time is O(n log n).
compare with O(n2) for sort methods of Chapter 2.
Heap Sort Uses a max priority queue that is implemented as a heap.
Initial put operations are replaced by a heap initialization step that takes O(n) time.
Min Tree Definition Each tree node has a value.
Value in any node is the minimum value in the subtree for which that node is the root.
Equivalently, no descendent has a smaller value.
Min Tree Example Root has minimum element.
2 4 9 3 4 8 7 9 9
Max Tree Example Root has maximum element.
9 4 9 8 4 2 7 3 1
Min Heap Definition complete binary tree
min tree
Min Heap With 9 Nodes Complete binary tree with 9 nodes.
Min Heap With 9 Nodes Complete binary tree with 9 nodes that is also a min tree.
Comments