LOGBOOK

HELP

Quiz Entry - updated: 2026.11.26

How can a priority queue be used to sort a sequence, and what does the running time depend on?

Insert every element into the priority queue, then call removeMin() until it is empty: the elements come out in ascending order. How fast this is depends entirely on how the priority queue is implemented.

The algorithm, called PQ-Sort, has two phases:

Algorithm PQ-Sort(S, C)
  P ← empty priority queue using comparator C
  while not S.isEmpty()            // phase 1: fill the queue
    e ← S.remove(S.first())
    P.insert(e, null)
  while not P.isEmpty()            // phase 2: drain it in order
    e ← P.removeMin().key()
    S.addLast(e)

The element itself serves as the key (the value is unused), and the comparator C defines what "ascending" means. Phase 2 works because each removeMin() returns the smallest remaining element, so appending them one after another builds the sorted sequence.

PQ-Sort is a scheme rather than a single algorithm: it does $n$ inserts and $n$ removeMins, and their cost is whatever the chosen implementation charges. Plug in an unsorted list and it becomes selection-sort, a sorted list gives insertion-sort, both $O(n^2)$; plug in a heap and it becomes heap-sort, $O(n \log n)$.

Go deeper:

From Quiz: ADS / Priority Queues and Heaps | Updated: Nov 26, 2026