use std::collections::BinaryHeap;
fn main() {
let mut max_heap = BinaryHeap::new(); // lower half
let mut min_heap = BinaryHeap::new(); // upper half (store negative values to simulate min-heap)
let nums = vec![5, 15, 1, 3];
for &num in &nums {
if max_heap.peek().map_or(true, |&x| num <= x) {
max_heap.push(num);
} else {
min_heap.push(-num);
}
// Balance heaps
if max_heap.len() > min_heap.len() + 1 {
if let Some(top) = max_heap.pop() {
min_heap.push(-top);
}
} else if min_heap.len() > max_heap.len() {
if let Some(top) = min_heap.pop() {
max_heap.push(-top);
}
}
}
// Calculate median
let median = if max_heap.len() == min_heap.len() {
(*max_heap.peek().unwrap() + (-*min_heap.peek().unwrap())) as f64 / 2.0
} else {
*max_heap.peek().unwrap() as f64
};
println!("Median: {:.1}", median);
}After inserting 5, 15, 1, 3, the two heaps balance to lower half: [3,1], upper half: [5,15]. The median is the average of 3 and 5, which is 4.0.
Using two heaps splits the data into lower and upper halves. The max-heap stores the smaller half, the min-heap stores the larger half. Balancing them keeps the median at the top of one or average of tops, allowing O(1) median retrieval.
use std::collections::BinaryHeap;
fn main() {
let mut max_heap = BinaryHeap::new();
let mut min_heap = BinaryHeap::new();
let nums = vec![10, 20, 30];
for &num in &nums {
if max_heap.peek().unwrap() >= &num {
max_heap.push(num);
} else {
min_heap.push(-num);
}
if max_heap.len() > min_heap.len() + 1 {
if let Some(top) = max_heap.pop() {
min_heap.push(-top);
}
} else if min_heap.len() > max_heap.len() {
if let Some(top) = min_heap.pop() {
max_heap.push(-top);
}
}
}
println!("Median: {}", max_heap.peek().unwrap());
}The code calls max_heap.peek().unwrap() without checking if max_heap is empty. On the first iteration, max_heap is empty, so unwrap panics causing runtime error.
if max_heap.peek().map_or(true, |&x| num <= x) { max_heap.push(num) } else { min_heap.push(-num) }
The push method calls are missing semicolons, causing syntax errors. Adding semicolons fixes the syntax.
After inserting all numbers and balancing, max-heap contains [8,7,6,5] and min-heap contains [10,12]. So max-heap has 4 elements, min-heap has 2.
