Concept Flow - Build Heap from Array Heapify
Start with array
Find last non-leaf node
Heapify node
Move to previous node
Repeat heapify until root
Heap built
Start from the last non-leaf node and heapify each node up to the root to build the heap.
fn build_heap(arr: &mut [i32]) {
let n = arr.len();
for i in (0..n / 2).rev() {
heapify(arr, n, i);
}
}| Step | Operation | Node Index | Heapify Action | Array State | Visual State |
|---|---|---|---|---|---|
| 1 | Start build_heap | - | - | [4, 10, 3, 5, 1] | 4 -> 10 -> 3 -> 5 -> 1 -> null |
| 2 | Heapify at index 1 | 1 | Compare with children (5,1), no swap needed (10 largest) | [4, 10, 3, 5, 1] | 4 -> 10 -> 3 -> 5 -> 1 -> null (no change) |
| 3 | Heapify at index 0 | 0 | Compare with children (10,3), swap with 10 | [10, 4, 3, 5, 1] | 10 -> 4 -> 3 -> 5 -> 1 -> null |
| 4 | Heapify at index 1 | 1 | Compare with children (5,1), swap with 5 | [10, 5, 3, 4, 1] | 10 -> 5 -> 3 -> 4 -> 1 -> null |
| 5 | Heap built | - | - | [10, 5, 3, 4, 1] | 10 -> 5 -> 3 -> 4 -> 1 -> null |
| Variable | Start | After Step 2 | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|---|
| arr | [4, 10, 3, 5, 1] | [4, 10, 3, 5, 1] | [10, 4, 3, 5, 1] | [10, 5, 3, 4, 1] | [10, 5, 3, 4, 1] |
| i (heapify index) | - | 1 | 0 | 1 | - |
Build Heap from Array (Heapify): - Start from last non-leaf node (n/2 -1) down to 0 - Heapify each node to maintain max heap property - Heapify swaps node with largest child if needed - Repeat until root is heapified - Result: array represents a max heap
heapify process when building a heap from an array?heapify function on an array slice arr starting at index i with heap size n?&mut arr.i and n are usually copied values, so pass by value.build_heap(&mut arr)? Assume build_heap calls heapify correctly to build a max-heap.
fn main() {
let mut arr = [3, 9, 2, 1, 4, 5];
build_heap(&mut arr);
println!("{:?}", arr);
}fn heapify(arr: &mut [i32], i: usize, n: usize) {
let mut largest = i;
let l = 2 * i + 1;
let r = 2 * i + 2;
if l < n && arr[l] > arr[largest] {
largest = l;
}
if r < n && arr[r] > arr[largest] {
largest = r;
}
if largest != i {
arr.swap(i, largest);
heapify(arr, n, largest);
}
}
What is the bug in this code that prevents building a max-heap correctly?fn heapify(arr: &mut [i32], i: usize, n: usize).heapify(arr, n, largest);, which passes n as i and largest as n: wrong parameter order.heapify uses wrong parameter order -> Option A[7, 2, 6, 3, 9, 1] using the standard heapify approach. Which modification should you make to the heapify function to correctly build a min-heap instead of a max-heap?Pass the test and this pattern moves unknown