Download Efficient Data Structures: Priority Queues & Heaps for Comparable Items and more Slides Object Oriented Programming in PDF only on Docsity!
Priority Queues and Heaps
The Bag Interface
- A Bag: interface Bag { void insert(E obj); E extract(); //extract some element boolean isEmpty(); }
Examples: Stack, Queue, PriorityQueue
Priority Queue
- A Bag in which data items are Comparable
- lesser elements (as determined by compareTo() ) have higher priority
- extract() returns the element with the highest priority = least in the compareTo() ordering
- break ties arbitrarily
Priority Queue Examples
- Scheduling jobs to run on a computer
- default priority = arrival time
- priority can be changed by operator
- Scheduling events to be processed by an
event handler
- priority = time of occurrence
- Airline check-in
- first class, business class, coach
- FIFO within each class
Priority Queues as Lists
- Maintain as unordered list
- insert() puts new element at front โ O(1)
- extract() must search the list โ O(n)
- Maintain as ordered list
- insert() must search the list โ O(n)
- extract() gets element at front โ O(1)
- In either case, O(n 2
) to process n elements
Can we do better?
Important Special Case
- Fixed number of priority levels 0,...,p โ 1
- FIFO within each level
- Example: airline check-in
- insert() โ insert in appropriate queue โ O(1)
- extract() โ must find a nonempty queue โ O(p)
Heaps
- Binary tree with data at each node
- Satisfies the Heap Order Invariant :
- Size of the heap is โfixedโ at n. (But can usually double n if heap fills up) The least (highest priority) element of any subtree is found at the root of that subtree
Least element in any subtree is always found at the root of that subtree Note: 19, 20 < 35: we can often find smaller elements deeper in the tree!
Heaps
Balanced Heaps
These add two restrictions:
1. Any node of depth < d โ 1 has exactly 2
children, where d is the height of the tree
- implies that any two maximal paths (path from a root to a leaf) are of length d or d โ 1, and the tree has at least 2 d nodes
- All maximal paths of length d are to the left of
those of length d โ 1
Example of a Balanced Heap
d = 3
0 1 2 3 4 5 6 7 8 9 10 11 children of node n are found at 2n + 1 and 2n + 2
Store in an ArrayList or Vector
Store in an ArrayList or Vector
0 1 2 3 4 5 6 7 8 9 10 11 4 6 14 21 8 19 35 22 38 55 10 20 children of node n are found at 2n + 1 and 2n + 2 0 1 2 3 4 5 6 7 8 9 10 11 4 6 14 21 8 19 35 22 38 55 10 20
insert()
insert()