Top K Values with BinaryHeap
Keep the largest K values from a stream in a bounded min-heap using Reverse, then return them sorted from highest to lowest.
Code
use std::cmp::Reverse;
use std::collections::BinaryHeap;
fn top_k(values: &[i64], k: usize) -> Vec<i64> {
if k == 0 {
return Vec::new();
}
let mut heap: BinaryHeap<Reverse<i64>> = BinaryHeap::with_capacity(k + 1);
for &value in values {
heap.push(Reverse(value));
if heap.len() > k {
heap.pop();
}
}
let mut out: Vec<i64> = heap.into_iter().map(|Reverse(value)| value).collect();
out.sort_unstable();
out.reverse();
out
}
fn main() {
let values = [42, 7, 19, 3, 88, 23, 56, 91, 5];
println!("{:?}", top_k(&values, 3));
}
How it works
Top K Values with BinaryHeap is built around the functions top_k and main.
Iteration happens inside for &value in values — everything outside it runs once.
Applying it
The main signature reads fn top_k(values: &[i64], k: usize) -> Vec<i64>
main sequences top_k; executing the file runs that flow once.
Statements that matter
let mut out: Vec<i64> = heap.into_iter().map(|Reverse(value)| value).collect();
return Vec::new();
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Top K Values with BinaryHeap?
- Run the file on its own; every call resolves against the standard surface it already imports.
Report a problem with this exampleOpens a pre-filled issue on GitHub.