Memra

Priority queues

◈ 4 cards

A max-heap as an ADT: MAXIMUM in Θ(1), INSERT / EXTRACT-MAX / INCREASE-KEY in O(lg n) — the engine of Dijkstra, Prim, and Huffman.

From data structure to abstract type

A max-priority queue maintains a set of elements keyed by priority and supports four operations:

  • MAXIMUM(S) — return the element with the largest key — (it's the root).
  • EXTRACT-MAX(S) — remove and return that element — .
  • INSERT(S, x) — add .
  • INCREASE-KEY(S, x, k) — raise 's key to its current key — .

Backed by a max-heap, all four are cheap because every fix touches only one root-to-leaf (or leaf-to-root) path of length .

Two directions of repair

MAX-HEAPIFY moves a too-small value down. The priority-queue operations also need the opposite. INCREASE-KEY raises a key, which can only violate the property against the parent (the children are still smaller), so it walks up, swapping with the parent while the parent is smaller — exactly insertion sort's inner loop. EXTRACT-MAX saves , moves the last leaf to the root, shrinks, and MAX-HEAPIFYs down. INSERT is the slick trick: append the new element with key , then INCREASE-KEY it up to its real key — reusing one routine and guaranteeing the current-key precondition for any legal .

Worked example

Insert keys one at a time (each bubbles up). The root is now . Extract four times: you get in that order, each extract sifting the moved leaf back down. MAXIMUM then returns — the largest of the three survivors . The runnable exercise reproduces exactly this transcript.

This ADT is the workhorse of later modules: Dijkstra and Prim use a min-priority queue with DECREASE-KEY; Huffman repeatedly EXTRACT-MINs the two lightest nodes.

OperationCostRepair pathMAXIMUMΘ(1)read A[1]EXTRACT-MAXO(lg n)root → leafINSERTO(lg n)leaf → rootINCREASE-KEYO(lg n)leaf → rootEvery O(lg n) op walks one root-to-leaf path.
MAXIMUM only reads the root, so it is free. The other three each fix a single path of length ⌊lg n⌋ — which is the whole reason a heap backs this ADT.
01234before8341append834116new leafbubble up168413new maxA raised key moves up, never down.
INSERT in the worked transcript (0-indexed, as in the runnable exercise). The new key is appended, then walks *up* — MAX-HEAPIFY only walks down, which is why it cannot do this repair.
NORMAL ~/memra/learn/comp-372/priority-queues utf-8 LF