Recall queues also called FIFO? Standard queues prioritize
temporally; like standing in a line, first come first serve.
Priority queues are a generalization of the standard queue, and
prioritize by a key.
Priority queues contain entries =
{keys, values}
Seating on a fill plane
Operating system job control
Patient serving in the Emergency ward
Securities exchanges:
Bids: maximum buy price
Asks: minimum sell price
What would be the values and keys above?
/** Interface for a key-value pair entry **/ public interface Entry { public Object key(); public Object value(); }
The keys and values can be equal.
We also need same way
to compare keys. Another class Comparator.
Mathematically the comparator is a total ordering
relation
≤ (meaning less or equal) has properties:
Reflexivity : k ≤ k
Antisymmetry: if k1 ≤ k2 and k2 ≤ k1, then k1 = k2
Transitivity: if k1 ≤ k2 and k2 ≤ k3, then k1 ≤ k3
Java has Comparator interface with only one method;
int compareTo(Object o),
Known implementing classes are Byte, Character, Double, File, Float, Long, ObjectStreamField, Short, String, Integer, BigInteger, BigDecimal, Date, and CollationKey.
/** Comparator for 2D points under the standard lexicographic order. */ public class Lexicographic implements Comparator { int xa, ya, xb, yb; public int compare(Object a, Object b) throws ClassCastException { xa = ((Point2D) a).getX(); ya = ((Point2D) a).getY(); xb = ((Point2D) b).getX(); yb = ((Point2D) b).getY(); if (xa != xb) return (xb - xa); else return (yb - ya); } }
/** Interface for the priority queue ADT */ public interface PriorityQueue { /** Returns the number of items in the priority queue. */ public int size(); /** Returns whether the priority queue is empty. */ public boolean isEmpty(); /** Returns but does not remove an entry with minimum key. */ public Entry min() throws EmptyPriorityQueueException; /** Inserts a key-value pair and return the entry created. */ public Entry insert(Object key, Object value) throws InvalidKeyException; /** Removes and returns an entry with minimum key. */ public Entry removeMin() throws EmptyPriorityQueueException; }
Listed based, sorted and unsorted
Sorted based insert: the entries into the list based on the key order, and therefore the minimum key entry location is know.
Unsorted: must search for the minimal key entry in the list.
Method |
Unsorted List |
Sorted List |
size, isEmpty |
O(1) |
O(1) |
insert |
O(1) |
O(n) |
min, removeMin |
O(n) |
O(1) |
Algorithm: PQSort:(Sequence S, PriorityQueue Q)
for all Positions p in S do
Item i = S.remove(p)
Q.insert(i)
while ( !Q.isEmpty() ) do
Position p = Q.removeMin()
S.insertLast(p)
We can use either sorted or unsorted list priority queue. For both
the complexity or cost is O(n2)
Space
requirements? In place?