Section 14.16

Priority queue

Definition

A priority queue is an abstract data type, one defined by its operations rather than its memory layout, that stores items each with a key called its priority. Removing returns an item with the smallest key (a min-priority queue) or the largest (a max-priority queue), whatever the order of insertion. Other usual operations insert an item, read the first item without removing it, and change a stored item’s key. The usual implementation, a binary heap, inserts and removes in at most about log2n\log_2 n steps for nn items.

The idea

A timer service holds timers that expire 50, 10 and 30 milliseconds (ms) from now, created in that order, and must fire the 10 ms timer first. A first in, first out §14.14 (FIFO) queue would fire them in creation order. A sorted list finds the earliest at once but must search for each insertion’s place; an unsorted list inserts cheaply but searches on every removal.

A binary heap sits between the two lists. It keeps the items only partly ordered, every parent no larger than its children. That is enough to keep the smallest item at the top, and little enough that each change is repaired along a single path of the tree.

How it works

A binary min-heap stores nn items in an array §14.5 at positions 0 to n−1n - 1 and reads the array as a binary tree, in which each item has at most two children. Position 0 is the root. The item at position ii has its children at 2i+12i + 1 and 2i+22i + 2 and its parent at ⌊(i−1)/2⌋\lfloor (i - 1) / 2 \rfloor, where ⌊x⌋\lfloor x \rfloor is xx rounded down. The heap property holds throughout: every parent’s key is at most each of its children’s keys, so the root holds a smallest key. Siblings, and items in different branches, are not ordered.

Each operation restores the heap property.

  1. Insert: place the item at position nn, then sift it up: while its key is smaller than its parent’s key, swap the two.

  2. Remove the minimum: take the root, move the last item to position 0, then sift it down: while its key is larger than the smaller of its children’s keys, swap it with that child.

  3. Decrease a key: lower it, then sift the item up. Increase a key: raise it, then sift the item down.

  4. Delete an item: move the last item into its position, then sift that item up or down as its key requires.

A heap of nn items has ⌊log2n⌋+1\lfloor \log_2 n \rfloor + 1 levels, and each swap moves an item one level, so each operation needs at most ⌊log2n⌋\lfloor \log_2 n \rfloor swaps: 19 for a million items, since 219=524,288≤1,000,000<2202^{19} = 524{,}288 \le 1{,}000{,}000 < 2^{20}.

Equal priorities. A binary heap is not stable: items with equal keys leave in an order set by the history of operations, not by insertion. For insertion order among equals, give each item a sequence number from a counter that increases on every insert, and compare (priority, sequence number) pairs: priority first, sequence number only on a tie. No two pairs are then equal. The documentation of Python’s §12.23 heapq module §15.27 describes this pattern.

Changing priorities. A heap cannot search by item, so changing a key first needs the item’s position; otherwise finding it means scanning all nn positions.

Alternatives: a sorted linked list §14.6 returns the minimum in one step but needs up to nn steps per insert, acceptable when few items are pending; a balanced search tree §14.10 needs about log2n\log_2 n steps for every operation, including finding any item by its key.

Worked example

Equal keys. Insert 5a5_a, then 2, then 5b5_b, where 5a5_a and 5b5_b are two items with key 5.

  1. Insert 5a5_a: [5a][5_a].

  2. Insert 2 at position 1; its parent, position ⌊0/2⌋=0\lfloor 0 / 2 \rfloor = 0, holds 5a5_a, and 2<52 < 5, so they swap: [2,5a][2, 5_a].

  3. Insert 5b5_b at position 2; its parent, position ⌊1/2⌋=0\lfloor 1 / 2 \rfloor = 0, holds 2, which is smaller, so it stays: [2,5a,5b][2, 5_a, 5_b].

  4. Remove the minimum: return 2 and move 5b5_b to the root: [5b,5a][5_b, 5_a]. The child 5a5_a is not smaller, so the sift stops.

  5. The next removal returns 5b5_b, inserted after 5a5_a.

With pairs (key, sequence number), the items are (5,0)(5, 0), (2,1)(2, 1) and (5,2)(5, 2); after 2 leaves, (5,0)(5, 0) is smaller than (5,2)(5, 2) at the root, so they swap and (5,0)(5, 0) leaves next.

Changing a key. [2,5,7,9,6][2, 5, 7, 9, 6] is a valid min-heap: 2 is at most its children 5 and 7, and 5 at most its children 9 and 6. Lower the 9, at position 3, to 1. Its parent, position ⌊2/2⌋=1\lfloor 2 / 2 \rfloor = 1, holds 5, and 1<51 < 5: swap, giving [2,1,7,5,6][2, 1, 7, 5, 6]. Its new parent, position 0, holds 2, and 1<21 < 2: swap, giving [1,2,7,5,6][1, 2, 7, 5, 6]. Without the sift, [2,5,7,1,6][2, 5, 7, 1, 6] would return 2 first, although 1 is smaller.

Stated precisely

Let a binary min-heap hold keys k0,…,kn−1k_0, \dots, k_{n-1} at positions 0 to n−1n - 1. The heap property is k⌊(i−1)/2⌋≤kik_{\lfloor (i - 1) / 2 \rfloor} \le k_i for every ii with 1≤i<n1 \le i < n; it implies k0≤kik_0 \le k_i for every ii. In the notation of asymptotic complexity §14.2, where O(f(n))O(f(n)) means at most a constant times f(n)f(n) steps for large nn: reading the minimum is O(1)O(1); insert, remove-minimum, and decrease-key or delete at a known position are O(logn)O(\log n); finding an item without a stored position is O(n)O(n).

The keys must form a total order: for any two keys exactly one of less, equal and greater holds, consistently. With the tie rule, pairs of a priority pp and a sequence number ss compare as (p1,s1)<(p2,s2)(p_1, s_1) < (p_2, s_2) if and only if p1<p2p_1 < p_2, or p1=p2p_1 = p_2 and s1<s2s_1 < s_2. If sequence numbers never repeat, equal priorities leave in increasing ss, which is insertion order.

Limits and common mistakes

A priority queue does not prevent starvation §9.18, a ready item waiting forever because others are always chosen first: if urgent items keep arriving, a low-priority item never reaches the root. Aging, raising an item’s priority as it waits, prevents this through the key-change §5.29 operation.

The structure decides only removal order. It does not show that jobs meet their deadlines, nor prevent priority inversion §9.16, in which an urgent task waits for a resource that a less urgent task holds.

A key edited while its item is stored breaks the heap property without any error. So does a comparison that is not a consistent total order, such as floating-point keys that include NaN §4.49 (not a number), which compares false with every value.

A 32-bit sequence number incremented a million times per second wraps after 232/106≈42952^{32} / 10^6 \approx 4295 seconds, about 72 minutes, after which new items compare as older than all others. A 64-bit counter at that rate lasts more than 500,000 years.

Libraries differ: the C++ std::priority_queue returns the largest item by default, Python’s heapq the smallest.

The binary heap is unrelated to the heap that programs allocate memory from; the two share only the name.

Questions answered

How are equal priorities and changing priorities handled?

Equal priorities are handled by a tie rule built into the comparison, and changing priorities by an update that restores the heap’s order. The usual priority queue, a binary heap, keeps every parent’s key no larger than its children’s and is not stable: equal keys leave in an order set by the history of operations. For insertion order among equals, give each item a sequence number from a counter that increases on every insert, and compare (priority, sequence number) pairs; a 64-bit counter will not wrap around in practice.

To change a priority, either find the item through a handle (a stored record of its current position), change its key, and sift it up for a smaller key or down for a larger one, at most about log2n\log_2 n swaps for nn items; or insert a new entry and discard the old one when it reaches the top. Editing a stored key without either step makes the heap return wrong items silently.

Related entries: Queue and FIFO (§14.14), Balanced search tree (§14.10), Liveness property (§1.12), Starvation (§9.18).