A BinaryHeap is a priority queue implemented with a binary heap. It can be configured as either a Max heap (where the largest element is at the top) or a Min heap (where the smallest element is at the top).
Complexity:
- Insertion (
push): O(log n) - Popping the top element (
pop): O(log n) - Peeking at the top element (
peek): O(1)
Warning: It is a logic error to modify an item in a way that changes its Ord relationship with other items while it is in the heap. This can happen via Cell, RefCell, or unsafe code, and will corrupt the heap structure.
use heapless::binary_heap::{BinaryHeap, Max};
let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
heap.push(1).unwrap();
heap.push(5).unwrap();
heap.push(2).unwrap();
// Peek shows the most important item (5)
assert_eq!(heap.peek(), Some(&5));
// Pop items in order of priority
assert_eq!(heap.pop(), Some(5));
assert_eq!(heap.pop(), Some(2));
assert_eq!(heap.pop(), Some(1));
assert_eq!(heap.pop(), None);