Lecture 17
What Is a Priority Queue?
A regular queue (lecture 16) serves elements in the order they arrive — first in, first out. A priority queue serves elements in priority order — the element with the highest priority is always dequeued next, regardless of insertion order.
The three core operations are:
push(value)— insert an elementpop()— remove the highest-priority elementtop()— read the highest-priority element without removing it
Binary Heaps
The standard implementation of a priority queue is a binary max-heap: a complete binary tree where every node's value is ≥ the values of its children. The largest element always sits at the root.
A complete binary tree maps neatly onto an array. For a node at index i:
No pointers needed — the structure is encoded entirely by position.
Push — Sift Up
push appends the new element at the end of the array, then calls sift_up to restore the
heap property. sift_up repeatedly compares the element with its parent and swaps upward until
the element is no longer larger than its parent (or reaches the root).
Pop — Sift Down
pop removes the root (the maximum). To avoid a gap, it moves the last element into the
root position, then calls sift_down to restore the heap property. sift_down repeatedly swaps
the element with its largest child until neither child is larger (or the element reaches a
leaf).
Both push and pop are O(log n) because the heap height is ⌊log₂ n⌋ and each sift
operation does at most one swap per level.
Calling top() or pop() on an empty priority queue accesses data_[0] on an empty or
invalid array. Always check empty() first.
Min-Heap Variant
A min-heap serves the smallest element first. The only change is flipping the comparison in
sift_up and sift_down from > to <:
Everything else — the index arithmetic, the array layout, push and pop structure — stays
identical.
Exercises
Q1.
Without running the code, predict what this program prints.
Q2.
Without running the code, trace the heap array after each operation and predict the output.
Q3.
Each snippet has a bug related to the heap. Identify what's wrong.
Q4.
Implement push and pop for the priority queue below. Use the provided sift_up and
sift_down helpers.
Q5.
Implement sift_up and sift_down for the min-heap priority queue below. The min-heap
always serves the smallest element first.
Practice Problems
- Last Stone Weight — Easy
- Kth Largest Element in an Array — Medium
- K Closest Points to Origin — Medium
- Find Median from Data Stream — Hard