Binary heap
BinaryHeap<T> is a max-heap priority queue. push and pop are O(log n). The greatest Ord value comes out first.
Detailed Explanation
A binary heap is a complete binary tree in an array with the heap property: each parent is at least as large as its children (max-heap). BinaryHeap in the standard library is a max-heap. peek is the current maximum. pop removes it and restores the property. push inserts and sifts up.
You use it when you always need the current best item: Dijkstra's tentative distances, Huffman merging, "top k" of a stream, a scheduler. You do not use it for sorted iteration of all elements — that is n pops, O(n log n), and a Vec plus sort is simpler if the data is already complete. You do not use it as a map; there is no O(log n) delete-by-key in the std heap.
Because it is a max-heap, a min-heap of numbers is BinaryHeap of Reverse<T> or of a wrapper with a reversed Ord. Dijkstra stores (Reverse(dist), node) so the smallest distance pops first. Forgetting Reverse is the classic bug: the largest distance wins and the shortest-path algorithm becomes a longest-path grab.
BinaryHeap is not stable. Equal keys pop in unspecified order. It is not thread-safe. It does not support decrease-key; the usual Dijkstra in Rust pushes a new entry and ignores stale ones with a dist[] check. That is O((n + extra) log n) and is the accepted trade for not writing a custom heap.
When you reach for BinaryHeap: repeated extract-min/max. When you reach for BTreeMap: you need to find or delete an arbitrary key. When you reach for VecDeque: FIFO, not priority.
Code Examples
use std::cmp::Reverse;
use std::collections::BinaryHeap;
fn main() {
let mut max_h = BinaryHeap::new();
max_h.push(3);
max_h.push(10);
max_h.push(7);
println!("{:?}", max_h.pop()); // prints: Some(10)
let mut min_h = BinaryHeap::new();
min_h.push(Reverse(3));
min_h.push(Reverse(10));
println!("{:?}", min_h.pop()); // prints: Some(Reverse(3))
}Common Gotchas
`BinaryHeap` is a max-heap
Dijkstra and "smallest first" need `Reverse`. Without it the algorithm is quietly wrong.
No decrease-key
Push a new pair and skip stale pops when `dist[u]` is already better. Do not scan the heap.
Dumping the heap with `for` drains it in heap order, not sorted order
Collect and sort if you need a sorted list. Repeated `pop` is sorted; iteration is not a sort.