Complete the code to get the left child index in a heap array.
function leftChildIndex(parentIndex) {
return 2 * parentIndex [1] 1;
}The left child index in a heap is calculated as 2 * parentIndex + 1.
Complete the code to swap two elements in the heap array.
function swap(heap, i, j) {
const temp = heap[i];
heap[i] = heap[[1]];
heap[j] = temp;
}To swap elements at indices i and j, assign heap[i] = heap[j].
Fix the error in the bubbleDown function to correctly compare and swap with the smaller child in a min-heap.
function bubbleDown(heap, index) {
const left = 2 * index + 1;
const right = 2 * index + 2;
let smallest = index;
if (left < heap.length && heap[left] [1] heap[smallest]) {
smallest = left;
}
if (right < heap.length && heap[right] < heap[smallest]) {
smallest = right;
}
if (smallest !== index) {
swap(heap, index, smallest);
bubbleDown(heap, smallest);
}
}In a min-heap, we swap if the child is smaller than the current smallest, so the comparison is <.
Fill both blanks to complete the extractMin function that removes the smallest element and restores the heap.
function extractMin(heap) {
if (heap.length === 0) return null;
const min = heap[0];
heap[0] = heap[[1]];
heap.[2]();
bubbleDown(heap, 0);
return min;
}Replace root with last element (heap.length - 1) and remove last element with pop().
Fill all three blanks to complete the bubbleDown function for a max-heap that swaps with the larger child.
function bubbleDown(heap, index) {
const left = 2 * index + 1;
const right = 2 * index + 2;
let largest = index;
if (left < heap.length && heap[left] [1] heap[largest]) {
largest = left;
}
if (right < heap.length && heap[right] [2] heap[largest]) {
largest = right;
}
if (largest !== index) {
swap(heap, index, largest);
bubbleDown(heap, [3]);
}
}For max-heap, swap if child is greater (use > for comparison), and recurse on largest child index.