Priority Queues
- A priority queue stores items as
(key, value)pairs - Smallest key (integer) = highest priority
- Items are removed in key order, not insertion order
Core operations:
| Method | What it does | Notes |
|---|---|---|
add(k, x) | Insert item with key k, value x | Always allowed |
remove_min() | Remove + return smallest-key item | Error if empty |
min() | Peek at smallest-key item (no removal) | Error if empty |
len(P) | Number of items | — |
is_empty() | True if no items | — |
Keys must satisfy total order relation: reflexive, antisymmetric, transitive
Sequence Based Priority Queue
Two Sequence-Based Approaches:
- Unsorted List
add->remove_min->min->
- Sorted List
add->remove_min->min->
There is a trade-off depending on which approach is used. It takes more time searching for the
minin an unsorted list, but maintaining a sorted list is harder as additions must preserve order
The ideal implementation is a heap:
- for both additions and searches
Priority Queue Sorting
- Any priority queue can be used to sort a sequence:
- Insert all elements
- Extract all elements with
remove_min()- Items come out in sorted order
Selection-Sort ->
- Phase 1: append each element
- Phase 2:
remove_minscans whole unsorted PQ
Insertion-Sort ->
- Phase 1: each add must find the right place
- Phase 2:
popfrom the front each time
Heap-Sort ->
- Phase 1:
addtakes time () - Phase 2:
remove_mintakes time ()