Rust's std::collections::BinaryHeap always pops the largest element; how do you make a job scheduler pop the earliest deadline first?
answer
- max-heap by Ord
- flip the comparison
- a wrapper in std::cmp
- Reverse((deadline, id))
basics
~10 sWrap each entry in std::cmp::Reverse, as in heap.push(Reverse((deadline, id))). Reverse flips Ord, so BinaryHeap's max-heap pops the smallest deadline first; an Ord impl that compares backwards also works.
solid answer
~40 s`BinaryHeap<T>` is a max-heap over `T: Ord`: `peek` and `pop` return the greatest element, and there is no min-heap type or flag. You invert the ordering instead. `std::cmp::Reverse<T>` is a tuple struct whose `Ord` compares the inner values backwards, so `BinaryHeap<Reverse<(u64, u32)>>` pops the earliest deadline, ties broken by the smaller id because tuples compare field by field. Unwrap on the way out with `while let Some(Reverse((deadline, id))) = heap.pop()`. The alternative is a hand-written `Ord` on the job type that compares `other` to `self`, as std's Dijkstra example does; it drops the wrapper but makes the type sort backwards everywhere. Note that `iter()` visits elements in arbitrary order, and `into_sorted_vec()` sorts ascending by the heap's `Ord`, which for `Reverse` means latest deadline first.
code
rust · 23 linesuse std::cmp::Reverse;
use std::collections::BinaryHeap;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Job {
deadline_ms: u64,
id: u32,
}
fn main() {
let mut queue = BinaryHeap::new();
queue.push(Reverse(Job { deadline_ms: 900, id: 1 }));
queue.push(Reverse(Job { deadline_ms: 150, id: 2 }));
queue.push(Reverse(Job { deadline_ms: 400, id: 3 }));
// The smallest deadline is on top because Reverse flips Ord.
if let Some(Reverse(next)) = queue.peek() {
println!("next due: job {} at {} ms", next.id, next.deadline_ms);
}
while let Some(Reverse(job)) = queue.pop() {
println!("run job {} (deadline {} ms)", job.id, job.deadline_ms);
}
}go deeper
Know that BinaryHeap pops the largest element and that std::cmp::Reverse is the standard way to get the smallest instead.
Explain why Reverse works: the heap only consults Ord, and Reverse swaps the comparison. Show the tuple tie-break and unwrapping with a pattern.
Weigh Reverse against a reversed Ord impl, and know the traps: arbitrary iter() order, into_sorted_vec's direction under Reverse, and O(n) construction from a Vec.
Prefer the inversion visible at the queue's declaration over one hidden in a widely shared type, so other code sorting that type is not silently reversed.
## BinaryHeap is a max-heap `std::collections::BinaryHeap<T>` is std's priority queue, documented as **a max-heap**. For any `T: Ord`, `peek()` returns the greatest element in O(1), and `pop()` removes it in O(log n). There is no `MinHeap` type and no constructor flag that flips the direction. "Greatest" means whatever `T`'s `Ord` implementation says, so the way to get a min-heap is to **change the ordering the heap sees**. A job scheduler wants the opposite of the default: the **earliest deadline** must come out first. Two idioms do it, and std's own docs name both: wrap the values in `core::cmp::Reverse` (re-exported as `std::cmp::Reverse`), or write an `Ord` implementation that compares backwards. ## Option one: `Reverse` `Reverse<T>` is a one-field tuple struct, `pub struct Reverse<T>(pub T)`. Its `PartialOrd` and `Ord` call the inner value's comparison with the arguments swapped, so `Reverse(1) > Reverse(5)`. Inside a max-heap, the element with the **smallest** inner value is therefore the greatest and comes out first. - Push with `heap.push(Reverse(job))` or collect with `.map(Reverse)`. - Pop with a pattern that unwraps it: `while let Some(Reverse(job)) = heap.pop()`. - Your own type stays untouched; it can keep a natural, derived ascending `Ord` for every other use. ## Option two: a hand-written `Ord` The alternative is an `Ord` impl that compares `other` to `self` instead of `self` to `other`. std's module documentation uses exactly this for its Dijkstra example, so the frontier pops the lowest cost first. The rules for a hand-written impl are the comparison traits' rules: `PartialOrd` must agree with `Ord` (the usual body is `Some(self.cmp(other))`) and `Eq` must agree with both. The trade-off: | | `Reverse` wrapper | Reversed `Ord` impl | |---|---|---| | Where the inversion lives | at each push and pop site | inside the type | | Effect on sorting the type elsewhere | none | everything sorts backwards | | Boilerplate | none | `Ord` plus `PartialOrd` | | Reader surprise | low, visible in the type | high unless documented | ## Ordering by more than one key A scheduler needs a **tie-break**, or two jobs with the same deadline pop in an unspecified order. Put the keys in a tuple or derive `Ord` on a struct whose fields are in priority order: `Reverse((deadline_ms, id))` pops the earliest deadline, then the smaller id. Derived `Ord` compares fields top to bottom, so field order is the priority order. ## Things that surprise people 1. **`iter()` is not priority order.** `BinaryHeap::iter` visits the underlying vector in arbitrary order; only repeated `pop()` yields elements best-first. 2. **`into_sorted_vec()` sorts ascending by the heap's own `Ord`.** For a `BinaryHeap<Reverse<u32>>` built from 5, 1, 9, 3 it returns `[Reverse(9), Reverse(5), Reverse(3), Reverse(1)]` — ascending as `Reverse` values, which is descending as numbers. 3. **Building from a Vec is O(n).** `BinaryHeap::from(vec)` heapifies in place, while pushing one at a time degrades to O(n log n) when values arrive in ascending order. 4. **`f64` keys do not compile.** `push` requires `T: Ord`, so `BinaryHeap<f64>` fails with E0277; making floats orderable belongs with the comparison traits. 5. **`Reverse` keeps the payload.** A pattern like `Reverse((deadline, id))` destructures in one step, so there is no reason to unwrap with `.0` chains. ## Reading a min-heap back out Because every element is wrapped, the unwrapping shows up wherever values leave the heap: - `heap.peek()` returns `Option<&Reverse<T>>`, so match `Some(Reverse(next))` to read the next deadline without removing it. - `heap.pop()` returns `Option<Reverse<T>>`; a `while let Some(Reverse(job))` loop drains in earliest-first order. - `heap.into_vec()` hands back the underlying vector in arbitrary order, still wrapped. If the wrapper becomes noisy, a small newtype such as `struct Due(Reverse<(u64, u32)>)` with a derived `Ord` can hide it behind your own methods while keeping the inversion explicit in one place. Keep the heap's job narrow: it answers "what is next?" cheaply. Changing a queued job's priority or removing one from the middle are not operations it offers.
- Why does the tuple inside Reverse((deadline, id)) matter for the scheduler?Tuples order lexicographically, so the deadline decides first and the id breaks ties. Without a tie-break, two jobs with equal deadlines pop in an order the heap does not specify, which makes runs hard to reproduce. Putting the id second gives a deterministic order, the smaller id first under `Reverse`.
- When would you choose a reversed Ord impl over the Reverse wrapper?When the type exists only to live in this heap and every reader of it expects the inverted order, such as a search-frontier state. If the type is also sorted, compared or stored elsewhere, `Reverse` is safer: it keeps the type's natural order and makes the inversion visible at the heap's declaration.
- Call BinaryHeap::new_min() or pass a flag to get a min-heap.
- Iterating the heap with iter() yields elements in priority order.
- Reverse only changes iteration order, not what pop returns.
- Negate the deadline with a minus sign, even for u64 values.
- into_sorted_vec on a Reverse heap returns the smallest deadline first.