Priority Queue — Definition, Formula & Example
A priority queue is a collection where every item carries a priority, and the next item removed is always the one with the highest priority, not the one that arrived first.
A (min-)priority queue is an abstract data type that maintains a finite multiset of elements whose keys come from a totally ordered set. It supports , , and , which removes and returns an element of smallest key. Many versions also support . A max-priority queue is defined the same way with largest key. The standard implementation is a binary heap. It is a complete binary tree stored in an array, with each parent's key no greater than its children's keys. It gives insert and extract-min and find-min.
Key Formula
Where:
- = Number of items currently in the priority queue
- = Adds an item with its priority key
- = Reports the most urgent item (smallest key) without removing it
- = Removes and returns the most urgent item. The costs shown are for the usual binary heap implementation
Worked Example
Problem: A print server keeps jobs in a min-priority queue, where a lower number means more urgent. Starting from an empty queue, it performs these operations in order: insert 7, insert 3, extract-min, insert 9, insert 1, extract-min, extract-min. Which job does each extract-min return, and what is left at the end?
Step 1: After inserting 7 and then 3, the queue holds {3, 7}. Extract-min returns the smallest key, 3, even though job 7 arrived first.
Step 2: Insert 9 and then 1. The queue holds {1, 7, 9}. Extract-min returns 1, the newest job, because it is the most urgent.
Step 3: The last extract-min returns 7. With a binary heap, each of these operations takes time or less.
Answer: The three extract-min calls return 3, 1, and 7, in that order, and job 9 is left waiting. An ordinary first-in, first-out queue would have returned 7, 3, and 9 instead.
Why It Matters
Priority queues are central to the greedy algorithms you meet in a discrete math or data structures course. Dijkstra's shortest-path algorithm uses one to pick the next closest vertex, and Prim's algorithm uses one to pick the cheapest edge. Huffman coding builds file-compression codes by repeatedly extracting the two least frequent symbols. Operating systems also use priority queues to decide which process runs next.
Common Mistakes
Mistake: Assuming the heap array is sorted, so the second-smallest item must be at index 1 and the largest at the end.
Correction: The heap property only says each parent's key is no greater than its children's keys. For example, [1, 3, 9, 7] is a valid min-heap array, yet the 9 comes before the 7. Only the root is guaranteed to be the minimum, which is why extract-min must run sift-down to restore order.
