Heaps in practice
After this: Use heapq and PriorityQueue, and know their limits.
On this page · 7 sections · 4 checks
You have built a heap by hand, so you know how one works inside. In a real program you do not need to write sift up yourself. Python and Java both come with a heap, and each one is an array heap like ours, with the same costs.
- Python has the
heapqmodule: a set of functions that treat a plain list as a heap. - Java has the
PriorityQueueclass, which keeps its array hidden inside an object.
Here are the three jobs you already know, under their library names.
| Job | Python heapq | Java PriorityQueue | Cost |
|---|---|---|---|
| Push | heapq.heappush(h, x) | pq.add(x) | O(log n) |
| Pop the smallest | heapq.heappop(h) | pq.poll() | O(log n) |
| Peek | h[0] | pq.peek() | O(1) |
A priority together with an item
So far our heaps have held bare numbers. A real queue holds things, such as jobs or patients, and each thing has a priority.
In Python, push a : (priority, item). Python compares two tuples one element at a time, starting with the first. So the priority decides the order, and the item stays with its priority.
In Java, give PriorityQueue a : an object that says which of two items comes first. Here it reads the priority out of each Job.
import heapq
jobs = [] # heapq works on a plain listheapq.heappush(jobs, (3, "backup")) # (priority, item): the priority is compared firstheapq.heappush(jobs, (1, "page on-call"))heapq.heappush(jobs, (2, "rebuild index"))print(jobs[0]) # peek: the smallest is at index 0while jobs: priority, job = heapq.heappop(jobs) print(priority, job)(1, 'page on-call') 1 page on-call 2 rebuild index 3 backup
record Job(int priority, String name) {}
PriorityQueue<Job> jobs = new PriorityQueue<>(Comparator.comparingInt(Job::priority));jobs.add(new Job(3, "backup"));jobs.add(new Job(1, "page on-call"));jobs.add(new Job(2, "rebuild index"));System.out.println(jobs.peek()); // peek: the smallest is at the rootwhile (!jobs.isEmpty()) { Job job = jobs.poll(); System.out.println(job.priority() + " " + job.name());}Job[priority=1, name=page on-call] 1 page on-call 2 rebuild index 3 backup
Here is how to read it. Three jobs go in with priorities 3, 1 and 2. To "page on-call" means to alert the engineer on duty. The first printed line is a peek: it shows the job with priority 1 and does not remove it. The loop then pops until the heap is empty, and the jobs come out in the order 1, 2, 3.
Largest first
By default, both libraries give the smallest first. To get the largest first, change what "smallest" means.
- In Python, push the negative of each value. The scores 40, 75 and 60 become −40, −75 and −60. The smallest of those is −75, so pop returns it, and you turn it back into 75. Python 3.14 and later also have
heapq.heappush_maxandheapq.heappop_max, but negating works in every version. - In Java, pass
Comparator.reverseOrder(), which flips the comparison.
A heap that keeps the largest at the root is called a .
import heapq
scores = [40, 75, 60]top = []for s in scores: heapq.heappush(top, -s) # negate: the largest score is now the smallest numberprint(-heapq.heappop(top), -heapq.heappop(top))75 60
PriorityQueue<Integer> top = new PriorityQueue<>(Comparator.reverseOrder()); // flips the rule: largest firstfor (int s : new int[] {40, 75, 60}) top.add(s);System.out.println(top.poll() + " " + top.poll());75 60
The array is not sorted
If you print a heap, you see the array in heap order, as you did in the earlier lessons. This is plain to see in Python's heapq, because the heap is an ordinary list. Java's PriorityQueue hides its array, but it goes through that array in the same order. So a for-each loop, toString and stream() all give heap order, not sorted order. Only polling until the queue is empty gives sorted order.
import heapq
h = []for v in [5, 3, 8, 1]: heapq.heappush(h, v)print(h) # the list in heap order: not sortedprint(sorted(h)) # a sorted copy; the heap is untouched[1, 3, 8, 5] [1, 3, 5, 8]
PriorityQueue<Integer> pq = new PriorityQueue<>();for (int v : new int[] {5, 3, 8, 1}) pq.add(v);System.out.println(pq); // printing walks the array in heap order: not sortedList<Integer> drained = new ArrayList<>();while (!pq.isEmpty()) drained.add(pq.poll()); // only polling gives sorted orderSystem.out.println(drained);[1, 3, 8, 5] [1, 3, 5, 8]
Changing a priority
Suppose a job is waiting in the heap and becomes more urgent. Neither library can update it, because neither one knows where an item sits in its array. Finding it would mean looking through the whole array, which is O(n). The operation that moves an item to a new priority is called decrease-key, and neither library has it.
The usual method is to leave the old entry where it is and push a new one. Say the backup job has priority 3 and becomes priority 1.
- Push the job again with priority 1. The heap now holds two backup entries.
- A pop returns the backup entry with priority 1. Run the job, and write down that it is done.
- Later, a pop returns the old entry with priority 3. This out-of-date entry is called a stale entry. The job is already done, so skip it.
To spot stale entries, keep a set of finished jobs, or keep a version number in each entry. The shortest-paths tutorial also pushes again and skips stale entries in Dijkstra's algorithm, and it uses its distance table to spot them.
Other operations
| Operation | Python | Java | Cost |
|---|---|---|---|
| Build from a whole collection | heapq.heapify(h) | new PriorityQueue<>(items) | O(n) |
| Remove any item | h.remove(x) then heapq.heapify(h) | pq.remove(x) | O(n) |
| Change a priority | not available | not available | not applicable |
Check yourself
jobs holds the entries (3, 'backup')Job(3, "backup"), (1, 'page on-call')Job(1, "page on-call") and (2, 'rebuild index')Job(2, "rebuild index"). What does heapq.heappop(jobs)jobs.poll() return?
You need the largest value first. What is the standard way?
What do the two lines print?
import heapq
h = []for v in [5, 3, 8, 1]: heapq.heappush(h, v)print(h) # the list in heap order: not sortedprint(sorted(h)) # a sorted copy; the heap is untouchedPriorityQueue<Integer> pq = new PriorityQueue<>();for (int v : new int[] {5, 3, 8, 1}) pq.add(v);System.out.println(pq); // printing walks the array in heap order: not sortedList<Integer> drained = new ArrayList<>();while (!pq.isEmpty()) drained.add(pq.poll()); // only polling gives sorted orderSystem.out.println(drained);A job already in the heap becomes more urgent. What does the standard library give you?
Connect
- Use Python's heapq on a plain list with (priority, item) tuples, and Java's PriorityQueue with a comparator.
- Get the largest first: negate the values in Python, or use Comparator.reverseOrder() in Java.
- Know that the heap array is not sorted, that going through a PriorityQueue gives array order, and that neither library can change a priority.