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 steps for 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 items in an array §14.5 at positions 0 to 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 has its children at and and its parent at , where is 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.
Insert: place the item at position , then sift it up: while its key is smaller than its parent’s key, swap the two.
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.
Decrease a key: lower it, then sift the item up. Increase a key: raise it, then sift the item down.
Delete an item: move the last item into its position, then sift that item up or down as its key requires.
A heap of items has levels, and each swap moves an item one level, so each operation needs at most swaps: 19 for a million items, since .
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 positions.
Handles: each item records its position, and every swap updates both items’ positions, so decrease-key finds the item at once.
Lazy deletion: insert a new entry with the new key and mark the old entry removed; a removed entry that reaches the root is discarded. The
heapqdocumentation describes this method too.
Alternatives: a sorted linked list §14.6 returns the minimum in one step but needs up to steps per insert, acceptable when few items are pending; a balanced search tree §14.10 needs about steps for every operation, including finding any item by its key.
Worked example
Equal keys. Insert , then 2, then , where and are two items with key 5.
Insert : .
Insert 2 at position 1; its parent, position , holds , and , so they swap: .
Insert at position 2; its parent, position , holds 2, which is smaller, so it stays: .
Remove the minimum: return 2 and move to the root: . The child is not smaller, so the sift stops.
The next removal returns , inserted after .
With pairs (key, sequence number), the items are , and ; after 2 leaves, is smaller than at the root, so they swap and leaves next.
Changing a key. 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 , holds 5, and : swap, giving . Its new parent, position 0, holds 2, and : swap, giving . Without the sift, would return 2 first, although 1 is smaller.
Stated precisely
Let a binary min-heap hold keys at positions 0 to . The heap property is for every with ; it implies for every . In the notation of asymptotic complexity §14.2, where means at most a constant times steps for large : reading the minimum is ; insert, remove-minimum, and decrease-key or delete at a known position are ; finding an item without a stored position is .
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 and a sequence number compare as if and only if , or and . If sequence numbers never repeat, equal priorities leave in increasing , 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 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 swaps for 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).