int[] heap = {1, 3, 6, 5, 9, 8}; // Extract min operation removes 1 and bubbles down // Resulting heap array after bubble down?
After removing 1, the last element 8 moves to root. Bubble down swaps 8 with smaller child 3, then 8 with 5. Final heap is [3, 5, 6, 8, 9].
int[] heap = {20, 18, 15, 13, 10, 12}; // Extract max removes 20 and bubbles down // Resulting heap array after bubble down?
After removing 20, last element 12 moves to root. Bubble down swaps 12 with larger child 18, then 12 with 13. Final heap is [18, 13, 15, 12, 10].
void BubbleDown(int[] heap, int index, int size) { int smallest = index; int left = 2 * index + 1; int right = 2 * index + 2; if (left < size && heap[left] < heap[smallest]) smallest = left; if (right < size && heap[right] < heap[smallest]) smallest = right; if (smallest != index) { int temp = heap[index]; heap[index] = heap[smallest]; heap[smallest] = temp; BubbleDown(heap, smallest, size); } }
Recursive call must be BubbleDown(heap, smallest, size) to continue bubbling down at the swapped child. Using 'index' causes infinite recursion.
First, the root is replaced by the last element (1). Then comparisons and swaps happen repeatedly to restore heap order.
int[] heap = {2, 4, 3, 8, 10, 15, 20}; // Extract min twice with bubble down each time // What is the heap array after these two extractions?
First extract removes 2, last element 20 moves to root, bubble down swaps 20 with 3, then 20 with 15. Heap after first extract: [3, 4, 15, 8, 10, 20]. Second extract removes 3, last element 20 moves to root, bubble down swaps 20 with 4, then 20 with 8. Final heap: [4, 8, 15, 20, 10].
