08-heaps
Min-Heap Pop (Sift Down)
Remove the minimum value, move the last item to the root, and sift downward.
Algorithm
Steps
- Store the heap in an array.
- Compare parent and child indexes instead of building explicit tree nodes.
- Swap only when the heap order is violated.
- Print the deterministic final heap state for replay comparison.
Complexity
- Time: O(log n)
- Space: O(1) extra
sift down
After removing the root, the last value moves to the root and swaps with the smaller child until order is restored.
Visual walkthrough
Rust DSA Implementation
basic.rs
fn list_string(values: &[i32]) -> String {
format!("[{}]", values.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))
}
fn heap_insert(heap: &mut Vec<i32>, value: i32) {
heap.push(value);
let mut child = heap.len() - 1;
while child > 0 {
let parent = (child - 1) / 2;
if heap[parent] <= heap[child] { break; }
heap.swap(parent, child);
child = parent;
}
}
fn heap_pop(heap: &mut Vec<i32>) -> i32 {
let smallest = heap[0];
let last = heap.pop().unwrap();
heap[0] = last;
let mut parent = 0;
loop {
let left = parent * 2 + 1;
let right = left + 1;
if left >= heap.len() { break; }
let mut child = left;
if right < heap.len() && heap[right] < heap[left] { child = right; }
if heap[parent] <= heap[child] { break; }
heap.swap(parent, child);
parent = child;
}
smallest
}
fn main() { let mut heap = vec![1, 4, 2, 9, 6, 7]; let popped = heap_pop(&mut heap); println!("{} -> {}", popped, list_string(&heap)); }
Output
1 -> [2, 4, 7, 9, 6]
Implementation notes
- The heap is a mutable
Vec<i32>inmainand is passed toheap_pop(heap: &mut Vec<i32>) -> i32, so the helper mutates the caller's vector and returns the removed minimum value. let smallest = heap[0]copies the root value.heap.pop().unwrap()removes the last slot and assumes the heap is non-empty; the checked example starts with six elements.- The last value is written back with
heap[0] = last, producing the traced state[7, 4, 2, 9, 6]after removing1. - Child indexes are
usizevalues:left = parent * 2 + 1andright = left + 1.if left >= heap.len() { break; }stops when a parent has no children. - This is a min-heap. The right child is selected only when it exists and is
smaller than the left child:
heap[right] < heap[left]. if heap[parent] <= heap[child] { break; }stops once the parent is no larger than the selected child; otherwiseheap.swap(parent, child)mutates the vector in place.- The trace shows one sift-down swap, changing
[7, 4, 2, 9, 6]to[2, 4, 7, 9, 6], thenprintln!("{} -> {}", popped, list_string(&heap))prints1 -> [2, 4, 7, 9, 6].