Complete the code to get the index of the left child in a heap array.
int leftChildIndex = 2 * parentIndex [1] 1;
The left child of a node at index parentIndex in a heap is at 2 * parentIndex + 1.
Complete the code to find the parent index of a node in a heap array.
int parentIndex = (childIndex [1] 1) / 2;
The parent of a node at childIndex is at (childIndex - 1) / 2 in a zero-based heap array.
Fix the error in the code that checks if a heap property is violated between parent and child.
if (heap[parentIndex] [1] heap[childIndex]) { // swap to maintain heap property }
In a max-heap, the parent's value should be greater than the child's. We swap if heap[parentIndex] < heap[childIndex].
Fill both blanks to complete the code that inserts a new element into a max-heap and restores the heap property.
heap[index] = newValue; while (index [1] 0 && heap[parentIndex] [2] heap[index]) { swap(&heap[parentIndex], &heap[index]); index = parentIndex; parentIndex = (index - 1) / 2; }
The loop continues while index > 0 and the parent's value is less than the current node's value, to maintain max-heap property.
Fill all three blanks to complete the code that builds a max-heap from an unsorted array.
for (int i = (size / 2) - 1; i >= 0; i--) { heapify(heap, size, [1]); } void heapify(int heap[], int size, int root) { int largest = root; int left = 2 * root + [2]; int right = 2 * root + [3]; if (left < size && heap[left] > heap[largest]) largest = left; if (right < size && heap[right] > heap[largest]) largest = right; if (largest != root) { swap(&heap[root], &heap[largest]); heapify(heap, size, largest); } }
The heapify function is called with i as root. Left child index is 2 * root + 1 and right child index is 2 * root + 2.
