Salta al contenuto
Note per Studenti Priority Queues Report

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 (key,value)(key, value), with the key from a domain KK and the value from a domain VV.

java
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 (k,v)(k, v) with kk = student ID (unique identifier) and vv = 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 KK. 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).

java
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, min and removeMin return an arbitrary one among them.
  • size() and isEmpty() 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-kk 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 PP. Entries are appended at the end of the list for now, without reordering by priority.

Operation Output Entries in PP after the operation
insert(5, A) (5,A)(5, A) [(5,A)][(5,A)]
insert(3, B) (3,B)(3, B) [(5,A),(3,B)][(5,A), (3,B)]
insert(9, C) (9,C)(9, C) [(5,A),(3,B),(9,C)][(5,A), (3,B), (9,C)]
removeMin() (3,B)(3, B) [(5,A),(9,C)][(5,A), (9,C)]
isEmpty() false [(5,A),(9,C)][(5,A), (9,C)]
insert(7, D) (7,D)(7, D) [(5,A),(9,C),(7,D)][(5,A), (9,C), (7,D)]
min() (5,A)(5, A) [(5,A),(9,C),(7,D)][(5,A), (9,C), (7,D)]
removeMin() (5,A)(5, A) [(7,D),(9,C)][(7,D), (9,C)]
size() 2 [(7,D),(9,C)][(7,D), (9,C)]

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

S=S[1],…,S[n]S = S[1], \dots, S[n] is a sequence of entries with distinct integer keys (e.g. profiles with their number of followers) and k∈[1,n]k \in [1, n]. Find the kk entries with the largest keys with a priority queue QQ:

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 Q

Homework: complete the algorithm so that QQ never holds more than kk 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 SS 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>>, nn = number of entries:

  1. Unsorted: insertion is simple and fast, finding the minimum needs a scan.
  2. 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 minE

removeMin() is Θ(n)\Theta(n): 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 e

removeMin() removes the first entry: Θ(1)\Theta(1). Insertion scans until the first key ≥k\ge k or the end of the list: Θ(n)\Theta(n) in the worst case.

Summary

List insert() min() removeMin()
Unsorted Θ(1)\Theta(1) Θ(n)\Theta(n) Θ(n)\Theta(n)
Sorted Θ(n)\Theta(n) Θ(1)\Theta(1) Θ(1)\Theta(1)

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 O(log⁡n)O(\log n).

Versione ripasso

  • Entry (key,value)(key, value). 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-kk, scheduling, discrete-event simulation.
  • Evolution example: insert(5,A), insert(3,B), insert(9,C), removeMin() gives (3,B)(3,B); insert(7,D); min() and removeMin() give (5,A)(5,A); size() gives 2.
  • Top-kk with a priority queue, no sorting, works on streams.
  • Lists:
List insert() min() removeMin()
Unsorted Θ(1)\Theta(1) Θ(n)\Theta(n) Θ(n)\Theta(n)
Sorted Θ(n)\Theta(n) Θ(1)\Theta(1) Θ(1)\Theta(1)

Teoria collegata