let mut heap = vec![]; heap.push(10); // heapify up heap.push(4); // heapify up heap.push(15); // heapify up heap.push(20); // heapify up // Final heap array
After inserting 10, heap is [10]. Insert 4, heap is [10,4]. Insert 15, heapify up swaps 15 with 10: [15,4,10]. Insert 20, heapify up swaps 20 with 15: [20,15,10,4].
A binary heap must be a complete binary tree (all levels filled except possibly last, filled left to right) and must satisfy the heap order property (parent >= children for max-heap or parent <= children for min-heap).
fn pop_max(heap: &mut Vec<i32>) -> Option<i32> {
if heap.is_empty() {
return None;
}
let max = heap[0];
let last = heap.pop().unwrap();
if !heap.is_empty() {
heap[0] = last;
}
let mut i = 0;
while i < heap.len() {
let left = 2 * i + 1;
let right = 2 * i + 2;
let mut largest = i;
if left < heap.len() && heap[left] > heap[largest] {
largest = left;
}
if right < heap.len() && heap[right] > heap[largest] {
largest = right;
}
if largest == i {
break;
}
heap.swap(i, largest);
i = largest;
}
Some(max)
}If heap has one element, pop() removes it, then code assigns heap[0] = last, but heap is empty now, so heap[0] access causes panic (index out of bounds).
Insert 5 elements adds 5. Removing 2 elements subtracts 2. Remaining elements = 5 - 2 = 3.
let mut arr = vec![3, 9, 2, 1, 4, 5]; // heapify process to build max-heap // final array after heapify
Heapify transforms the array into a max-heap. After heapify, the array is [9, 4, 5, 1, 3, 2].
