Complete the code to swap two elements in the heap array.
fn swap(arr: &mut Vec<i32>, i: usize, j: usize) {
let temp = arr[[1]];
arr[i] = arr[j];
arr[j] = temp;
}We use i to get the element at index i to swap it with the element at index j.
Complete the code to get the left child index of a node in the heap.
fn left_child(i: usize) -> usize {
[1]
}The left child of a node at index i in a heap is at 2 * i + 1.
Fix the error in the heapify function to correctly compare and swap elements.
fn heapify(arr: &mut Vec<i32>, n: usize, i: usize) {
let mut largest = i;
let l = 2 * i + 1;
let r = 2 * i + 2;
if l < n && arr[l] [1] arr[largest] {
largest = l;
}
if r < n && arr[r] [1] arr[largest] {
largest = r;
}
if largest != i {
arr.swap(i, largest);
heapify(arr, n, largest);
}
}To build a max heap, we swap if the child is greater than the current largest.
Fill both blanks to complete the build_heap function that heapifies from the bottom up.
fn build_heap(arr: &mut Vec<i32>) {
let n = arr.len();
for i in (0..[1]).rev() {
heapify(arr, n, [2]);
}
}We start heapifying from the last non-leaf node at index n/2 down to 0, using i as the current index.
Fill all three blanks to complete the main function that builds a heap and prints it.
fn main() {
let mut arr = vec![4, 10, 3, 5, 1];
[1](&mut arr);
for [2] in 0..arr.len() {
print!("{} ", arr[[3]]);
}
println!();
}We call build_heap to create the heap, then print each element using the loop variable i.
