Complete the code to get the index of the left child in a heap array.
function leftChildIndex(parentIndex) {
return 2 * parentIndex [1] 1;
}The left child index in a heap array is calculated as 2 * parentIndex + 1.
Complete the code to get the index of the parent node in a heap array.
function parentIndex(childIndex) {
return Math.floor((childIndex [1] 1) / 2);
}The parent index is calculated as floor((childIndex - 1) / 2) in a heap array.
Fix the error in the code to check if a node has a right child in the heap array.
function hasRightChild(index, heapSize) {
return (2 * index + [1]) < heapSize;
}The right child index is 2 * index + 2, so we check if this is less than heapSize.
Fill both blanks to create a function that swaps two elements in a heap array.
function swap(heap, i, j) {
const temp = heap[1];
heap[2] = heap[j];
heap[j] = temp;
}To swap elements, use bracket notation with indices: heap[i] and heap[j].
Fill all three blanks to complete the siftDown function that maintains the heap property.
function siftDown(heap, index, heapSize) {
let largest = index;
const left = 2 * index + [1];
const right = 2 * index + [2];
if (left < heapSize && heap[left] > heap[[3]]) {
largest = left;
}
if (right < heapSize && heap[right] > heap[largest]) {
largest = right;
}
if (largest !== index) {
swap(heap, index, largest);
siftDown(heap, largest, heapSize);
}
}Left child index is 2*index+1, right child is 2*index+2, and compare heap[left] with heap[index].