Complete the code to insert an element into a max heap array.
void Insert(int[] heap, int value, ref int size) {
heap[size] = value;
int current = size;
size++;
while (current > 0 && heap[current] > heap[[1]]) {
int parent = (current - 1) / 2;
int temp = heap[current];
heap[current] = heap[parent];
heap[parent] = temp;
current = parent;
}
}We compare the current node with its parent to maintain the max heap property.
Complete the code to extract the maximum element from a max heap.
int ExtractMax(int[] heap, ref int size) {
if (size == 0) return -1;
int max = heap[0];
heap[0] = heap[size - 1];
size--;
int current = 0;
while (true) {
int left = 2 * current + 1;
int right = 2 * current + 2;
int largest = current;
if (left < size && heap[left] > heap[[1]]) largest = left;
if (right < size && heap[right] > heap[largest]) largest = right;
if (largest == current) break;
int temp = heap[current];
heap[current] = heap[largest];
heap[largest] = temp;
current = largest;
}
return max;
}We compare the left child with the current node to find the largest among them.
Fix the error in the code that checks if a sorted array can efficiently support insertion.
bool CanInsertEfficiently(int[] sortedArray) {
// Insertion in sorted array requires shifting elements
// Time complexity is O([1])
return false;
}Insertion in a sorted array requires shifting elements, which takes linear time O(n).
Fill both blanks to complete the explanation of why heaps are better than sorted arrays for priority queues.
Heaps allow [1] insertion and [2] extraction of the maximum element, both in O(log n) time, while sorted arrays have O(n) insertion and O(1) extraction.
Heaps provide efficient insertion and extraction operations, both in O(log n) time, unlike sorted arrays.
Fill all three blanks to complete the code that builds a max heap from an unsorted array.
void BuildMaxHeap(int[] arr, int size) {
for (int i = size / 2 - 1; i >= [1]; i--) {
Heapify(arr, size, [2]);
}
}
void Heapify(int[] arr, int size, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < size && arr[left] > arr[largest]) largest = left;
if (right < size && arr[right] > arr[largest]) largest = right;
if (largest != i) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
Heapify(arr, size, [3]);
}
}The loop starts from the last non-leaf node at index 0, calling Heapify on each node i, and Heapify recursively calls itself on the largest child.
