blob: acaea5941cb645be9eed0bc20d2660e36ef5f874 [file] [log] [blame]
Joel Galenson6f798712021-04-01 17:03:06 -07001use alloc::collections::BinaryHeap;
2use core::cmp::Ord;
3
4pub(crate) fn k_smallest<T: Ord, I: Iterator<Item = T>>(mut iter: I, k: usize) -> BinaryHeap<T> {
5 if k == 0 { return BinaryHeap::new(); }
6
7 let mut heap = iter.by_ref().take(k).collect::<BinaryHeap<_>>();
8
Joel Galensonb593e252021-06-21 13:15:57 -07009 iter.for_each(|i| {
Joel Galenson6f798712021-04-01 17:03:06 -070010 debug_assert_eq!(heap.len(), k);
11 // Equivalent to heap.push(min(i, heap.pop())) but more efficient.
12 // This should be done with a single `.peek_mut().unwrap()` but
13 // `PeekMut` sifts-down unconditionally on Rust 1.46.0 and prior.
14 if *heap.peek().unwrap() > i {
15 *heap.peek_mut().unwrap() = i;
16 }
Joel Galensonb593e252021-06-21 13:15:57 -070017 });
Joel Galenson6f798712021-04-01 17:03:06 -070018
19 heap
20}