← Back to Home

CITS2200 - Lecture 16
Priority Queues - Slides

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:

MethodWhat it doesNotes
add(k, x)Insert item with key k, value xAlways allowed
remove_min()Remove + return smallest-key itemError 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:

  1. Unsorted List
    • add ->
    • remove_min ->
    • min ->
  2. Sorted List
    • add ->
    • remove_min ->
    • min ->

There is a trade-off depending on which approach is used. It takes more time searching for the min in 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:
    1. Insert all elements
    2. Extract all elements with remove_min()
      • Items come out in sorted order

Selection-Sort ->

  • Phase 1: append each element
  • Phase 2: remove_min scans whole unsorted PQ

Insertion-Sort ->

  • Phase 1: each add must find the right place
  • Phase 2: pop from the front each time

Heap-Sort ->

  • Phase 1: add takes time ()
  • Phase 2: remove_min takes time ()

CITS2200 - Lecture 18