Complete the code to insert an element into a max heap array.
public void insert(int[] heap, int size, int value) {
heap[size] = value;
int current = 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;
}
}The parent index in a heap is calculated as (current - 1) / 2. This helps maintain the heap property during insertion.
Complete the code to remove the max element from a max heap and restore heap property.
public int extractMax(int[] heap, int size) {
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 value to maintain the max heap property.
Fix the error in the code that checks if a sorted array can efficiently insert an element.
public boolean canInsertEfficiently(int[] sortedArray, int value) {
int n = sortedArray.length;
for (int i = 0; i < n; i++) {
if (sortedArray[i] > value) {
// Need to shift elements to insert
return [1];
}
}
return true;
}Inserting into a sorted array requires shifting elements, so it is not efficient. Hence, return false.
Fill both blanks to complete the code that shows why heap is better than sorted array for insert and extract max.
public class HeapVsSortedArray { public static void main(String[] args) { int[] sortedArray = {1, 3, 5, 7, 9}; int[] heap = {9, 7, 5, 3, 1}; // Insert in sorted array is O([1]) // Insert in heap is O([2]) } }
Insertion in a sorted array requires shifting elements, so it takes O(n). In a heap, insertion takes O(log n) due to heapify up.
Fill all three blanks to complete the code that compares extract max operation in sorted array and heap.
public class ExtractMaxComparison { public static void main(String[] args) { int[] sortedArray = {1, 3, 5, 7, 9}; int[] heap = {9, 7, 5, 3, 1}; // Extract max in sorted array is O([1]) // Extract max in heap is O([2]) // Sorted array requires [3] to maintain order after extraction } }
Extract max in a sorted array is O(1) because max is at the end, but maintaining order requires shifting elements. In a heap, extract max is O(log n) due to heapify down.
