Created
August 8, 2023 02:45
-
-
Save leiless/7465b08600b45ef0bb1c450f8c1595da to your computer and use it in GitHub Desktop.
Rust maintain top K elements on the fly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::cmp::Reverse; | |
use std::collections::BinaryHeap; | |
#[inline] | |
fn maintain_top_k<T: Ord>(min_heap: &mut BinaryHeap<Reverse<T>>, val: T, top_k: usize) { | |
if min_heap.len() < top_k { | |
min_heap.push(Reverse(val)); | |
} else if top_k > 0 && val > min_heap.peek().unwrap().0 { | |
min_heap.pop(); | |
min_heap.push(Reverse(val)); | |
} | |
while min_heap.len() > top_k { | |
min_heap.pop(); | |
} | |
} | |
#[inline(always)] | |
fn maintain_top_k_finalize<T: Ord + Copy>(min_heap: BinaryHeap<Reverse<T>>) -> Vec<T> { | |
min_heap.into_sorted_vec().iter().map(|x| x.0).collect() | |
} | |
fn main() -> Result<(), Box<dyn std::error::Error>> { | |
let top_k = 3usize; | |
let mut min_heap = BinaryHeap::with_capacity(top_k); | |
let items = [3, 8, 0, 2, 6, 9, 5, 4, 7, 1]; | |
for i in items { | |
maintain_top_k(&mut min_heap, i, top_k); | |
} | |
let v: Vec<_> = maintain_top_k_finalize(min_heap); | |
println!("{:?}", v); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html
struct TopK<T>