Complete the code to insert an element into a max heap.
void insert(int heap[], int *size, int value) {
heap[*size] = value;
int i = *size;
(*size)++;
while (i > 0 && heap[i] > heap[[1]]) {
int parent = (i - 1) / 2;
int temp = heap[i];
heap[i] = heap[parent];
heap[parent] = temp;
i = parent;
}
}The parent index in a heap is calculated as (i - 1) / 2. We compare the current element 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[], int *size) {
if (*size == 0) return -1;
int max = heap[0];
heap[0] = heap[(*size) - 1];
(*size)--;
int i = 0;
while (2 * i + 1 < *size) {
int left = 2 * i + 1;
int right = 2 * i + 2;
int largest = i;
if (heap[left] > heap[largest]) largest = left;
if (right < *size && heap[right] > heap[largest]) largest = right;
if (largest == i) break;
int temp = heap[i];
heap[i] = heap[[1]];
heap[largest] = temp;
i = largest;
}
return max;
}We swap the current element with the largest child to maintain the max heap property during heapify down.
Fix the error in the code that checks if a sorted array can efficiently insert an element.
void insertSorted(int arr[], int *size, int value) {
int i = *size - 1;
while (i >= 0 && arr[i] [1] value) {
arr[i + 1] = arr[i];
i--;
}
arr[i + 1] = value;
(*size)++;
}To insert while keeping the array sorted in ascending order, shift elements greater than the new value to the right.
Fill both blanks to complete the code that shows why sorted arrays are inefficient for insertion.
void insertSortedInefficient(int arr[], int *size, int value) {
int i = *size - 1;
while (i >= 0 && arr[i] [1] value) {
arr[i + 1] = arr[i];
i--;
}
arr[i + 1] = value;
(*size)++;
// This loop can run up to [2] times, making insertion slow
}The loop shifts elements greater than the value, and in the worst case, it can shift all elements, up to the size of the array.
Fill all three blanks to complete the code that demonstrates why heaps are better than sorted arrays for priority queue operations.
typedef struct {
int data[100];
int size;
} Heap;
void insertHeap(Heap *h, int value) {
h->data[h->size] = value;
int i = h->size;
h->size++;
while (i > 0 && h->data[i] [1] h->data[[2]]) {
int parent = (i - 1) / 2;
int temp = h->data[i];
h->data[i] = h->data[parent];
h->data[parent] = temp;
i = parent;
}
}
int getMax(Heap *h) {
if (h->size == 0) return -1;
return h->data[[3]];
}In a max heap, the inserted element is compared with its parent at index (i - 1) / 2, swapping if greater. The maximum element is always at index 0.
