fn build_max_heap(arr: &mut [i32]) {
let n = arr.len();
for i in (0..n / 2).rev() {
heapify(arr, n, i);
}
}
fn heapify(arr: &mut [i32], n: usize, i: usize) {
let mut largest = i;
let left = 2 * i + 1;
let right = 2 * i + 2;
if left < n && arr[left] > arr[largest] {
largest = left;
}
if right < n && arr[right] > arr[largest] {
largest = right;
}
if largest != i {
arr.swap(i, largest);
heapify(arr, n, largest);
}
}
fn main() {
let mut arr = vec![4, 10, 3, 5, 1];
build_max_heap(&mut arr);
println!("{:?}", arr);
}The build_max_heap function starts heapifying from the last parent node down to the root. After heapifying, the array represents a max heap where each parent node is greater than its children. The correct max heap array is [10, 5, 3, 4, 1].
For an array of size 8, the non-leaf nodes are at indices 0 to 3 (4 nodes). The build process calls heapify once for each non-leaf node in the for loop, from i = 3 down to i = 0. Recursive calls may occur inside heapify, but the build function directly calls heapify 4 times.
fn heapify(arr: &mut [i32], n: usize, i: usize) {
let mut largest = i;
let left = 2 * i + 1;
let right = 2 * i + 2;
if left <= n && arr[left] > arr[largest] {
largest = left;
}
if right <= n && arr[right] > arr[largest] {
largest = right;
}
if largest != i {
arr.swap(i, largest);
heapify(arr, n, largest);
}
}The condition uses 'left <= n' and 'right <= n', but valid indices are from 0 to n-1. Using '<=' allows index n access, which is out of bounds and causes a panic.
fn build_min_heap(arr: &mut [i32]) {
let n = arr.len();
for i in (0..n / 2).rev() {
min_heapify(arr, n, i);
}
}
fn min_heapify(arr: &mut [i32], n: usize, i: usize) {
let mut smallest = i;
let left = 2 * i + 1;
let right = 2 * i + 2;
if left < n && arr[left] < arr[smallest] {
smallest = left;
}
if right < n && arr[right] < arr[smallest] {
smallest = right;
}
if smallest != i {
arr.swap(i, smallest);
min_heapify(arr, n, smallest);
}
}
fn main() {
let mut arr = vec![9, 4, 7, 1, -2, 6, 5];
build_min_heap(&mut arr);
println!("{:?}", arr);
}After building the min heap, the smallest element -2 is at the root. The heap property is maintained with parents smaller than children. The resulting array is [-2, 1, 5, 9, 4, 6, 7].
Although heapify on one node can take O(log n), the total cost of building the heap is O(n) because most nodes are near the leaves and require less work. The sum of all heapify calls results in linear time complexity.
