Priority Queues
In questa pagina 7
From queue to priority queue
A queue is FIFO: elements are inserted at the rear and removed from the front, so the removal order depends strictly on the insertion order (print jobs, queue at the post office).
A priority queue has similar operations (insert, remove), but removal depends on priority, not on insertion order. Each element has a key that represents its priority and the element with the highest priority is removed first (hospital triage: the most urgent patient is treated first, even if they arrived later).
Entry
An entry is a pair , with the key from a domain and the value from a domain .
public interface Entry<K, V> {
K getKey(); // returns the key of the entry
V getValue(); // returns the value of the entry
}Example: a student is an entry with = student ID (unique identifier) and = personal data, study programme, exam records.
Priority queue
A priority queue is a collection of entries whose keys represent priorities and come from a totally ordered universe . The keys are not necessarily distinct.
As an abstract data type it supports: find and remove the entry with the highest priority, insert a new entry. Its state changes dynamically as entries are inserted and removed.
Convention: the smaller the key, the higher the priority (as in a ranking). Some contexts use the opposite (larger key = higher priority).
public interface PriorityQueue<K, V> {
int size();
boolean isEmpty();
Entry<K, V> insert(K key, V value); // inserts and returns the new entry (key, value)
Entry<K, V> min(); // returns an entry with min key, without removing it
Entry<K, V> removeMin(); // returns and removes an entry with min key
}- min key = max priority.
- With several entries having the minimum key,
minandremoveMinreturn an arbitrary one among them. size()andisEmpty()are standard methods of any data structure; they are trivial (a counter) and not analysed.
Applications
- Shortest path search (Dijkstra's algorithm: e.g. a route planner explores paths by priority).
- Pattern discovery: top- patterns from large datasets, ranked by a quantitative attribute.
- Process scheduling: operating systems and network management serve requests by priority (QoS).
- Discrete-event simulation: events are handled in chronological order (only significant events are simulated, e.g. a customer arriving or leaving).
In all of them the priority queue is a controller that decides what happens next from the priority of the available events or tasks.
Example: evolution of a priority queue
Start from an empty . Entries are appended at the end of the list for now, without reordering by priority.
| Operation | Output | Entries in after the operation |
|---|---|---|
insert(5, A) |
||
insert(3, B) |
||
insert(9, C) |
||
removeMin() |
||
isEmpty() |
false | |
insert(7, D) |
||
min() |
||
removeMin() |
||
size() |
2 |
Conceptually only the entry with the minimum key matters, not the internal representation: the internal order depends on the data structure (list, heap).
Exercise: Top-k entries
is a sequence of entries with distinct integer keys (e.g. profiles with their number of followers) and . Find the entries with the largest keys with a priority queue :
Algorithm Top(S, k)
Input: sequence S of n entries with distinct integer keys; integer k in [1, n]
Output: the k entries of S with the largest keys
Q <- empty priority queue
for i <- 1 to n do
if (i <= k) then
Q.insert(S[i].getKey(), S[i].getValue())
else
... // to complete: Q must never contain more than k entries
return QHomework: complete the algorithm so that never holds more than entries, and prove it correct with a loop invariant (see Correctness and Loop InvariantsCorrectness means termination plus solving the problem; it is proved with basic proof techniques (example, counterexample, contradiction, induction) and, for loops, with an invariant shown to hold initially, to be preserved, and to imply the final state.Correctness and Loop Invariants →). The algorithm does not rely on sorting and works even when does not fit in memory (data stream).
Implementation with lists
Natural idea: store the entries in a list and scan it. Two options, analysed with a doubly linked list PositionalList<Entry<K,V>>, = number of entries:
- Unsorted: insertion is simple and fast, finding the minimum needs a scan.
- Sorted (ascending keys): finding the minimum is easy, insertion is more expensive.
Unsorted list
Method insert(k, x) // Theta(1)
e <- (k, x)
P.addLast(e)
return e
Method min() // Theta(n)
v <- P.first()
minE <- v.getElement()
while (P.after(v) != null) do
v <- P.after(v)
if (v.getElement().getKey() < minE.getKey()) then
minE <- v.getElement()
return minEremoveMin() is : all the elements must be scanned to find the minimum (then the entry is removed from the list).
Sorted list
Method min() // Theta(1)
return P.first().getElement()
Method insert(k, x) // Theta(n)
e <- (k, x)
v <- P.first()
while (v != null) do
if (v.getElement().getKey() >= k) then
P.addBefore(v, e) // new node preceding v
return e
else v <- P.after(v)
P.insertLast(e) // new node at the end of P
return eremoveMin() removes the first entry: . Insertion scans until the first key or the end of the list: in the worst case.
Summary
| List | insert() |
min() |
removeMin() |
|---|---|---|---|
| Unsorted | |||
| Sorted |
In both cases one operation is fast and the others are costly. A better compromise is the heap (see HeapsA heap is a complete binary tree whose entries satisfy the heap-order property, stored in an array by level numbering, which implements a priority queue with insert and removeMin in logarithmic time and can be built from n entries in linear time.Heaps →): insert() and removeMin() both in .
Versione ripasso
- Entry . Priority queue: entries with keys from a totally ordered universe, keys not necessarily distinct. Smaller key = higher priority.
- Interface:
size,isEmpty,insert(k, v),min(),removeMin(). Ties: an arbitrary entry among the minimum keys. - Uses: Dijkstra, top-, scheduling, discrete-event simulation.
- Evolution example:
insert(5,A),insert(3,B),insert(9,C),removeMin()gives ;insert(7,D);min()andremoveMin()give ;size()gives 2. - Top- with a priority queue, no sorting, works on streams.
- Lists:
| List | insert() |
min() |
removeMin() |
|---|---|---|---|
| Unsorted | |||
| Sorted |
- Sorted insert: scan up to the first key , then
addBefore. Unsortedmin: scan keeping the smallest. - Typical mistake: forgetting that "min key" means maximum priority, and that
removeMinon an unsorted list also costs . - Better: HeapsA heap is a complete binary tree whose entries satisfy the heap-order property, stored in an array by level numbering, which implements a priority queue with insert and removeMin in logarithmic time and can be built from n entries in linear time.Heaps → ( for both
insertandremoveMin).