int[] heap = {1, 3, 6, 5, 9, 8}; // Extract min (root) and bubble down int last = heap[heap.length - 1]; heap[0] = last; int size = heap.length - 1; int i = 0; while (true) { int left = 2 * i + 1; int right = 2 * i + 2; int smallest = i; if (left < size && heap[left] < heap[smallest]) smallest = left; if (right < size && heap[right] < heap[smallest]) smallest = right; if (smallest != i) { int temp = heap[i]; heap[i] = heap[smallest]; heap[smallest] = temp; i = smallest; } else { break; } } // Print heap array after extraction and bubble down System.out.println(java.util.Arrays.toString(java.util.Arrays.copyOf(heap, size)));
After removing the root (1), we replace it with the last element (8). Then bubble down swaps 8 with the smaller child 3, then 8 with 5, resulting in [3, 5, 6, 8, 9].
int[] heap = {20, 18, 15, 13, 10, 8, 9}; // Extract max (root) and bubble down int last = heap[heap.length - 1]; heap[0] = last; int size = heap.length - 1; int i = 0; while (true) { int left = 2 * i + 1; int right = 2 * i + 2; int largest = i; if (left < size && heap[left] > heap[largest]) largest = left; if (right < size && heap[right] > heap[largest]) largest = right; if (largest != i) { int temp = heap[i]; heap[i] = heap[largest]; heap[largest] = temp; i = largest; } else { break; } } // Print heap array after extraction and bubble down System.out.println(java.util.Arrays.toString(java.util.Arrays.copyOf(heap, size)));
After removing the root (20), we replace it with the last element (9). Then bubble down swaps 9 with the larger child 18, then 9 with 13, resulting in [18, 13, 15, 9, 10, 8].
int i = 0; while (true) { int left = 2 * i + 1; int right = 2 * i + 2; int smallest = i; if (left < size && heap[left] < heap[smallest]) smallest = left; if (right < size && heap[right] < heap[smallest]) smallest = right; if (smallest != i) { int temp = heap[i]; heap[i] = heap[smallest]; heap[smallest] = temp; i = smallest; } else { break; } }
If i is not updated to smallest after swapping, the loop keeps swapping the same elements endlessly, causing infinite loop.
After removing the root, the last element is placed at root. Bubble down moves it down to restore heap order.
int[] heap = {2, 4, 3, 7, 6, 5}; int size = heap.length; for (int count = 0; count < 2; count++) { int last = heap[size - 1]; heap[0] = last; size--; int i = 0; while (true) { int left = 2 * i + 1; int right = 2 * i + 2; int smallest = i; if (left < size && heap[left] < heap[smallest]) smallest = left; if (right < size && heap[right] < heap[smallest]) smallest = right; if (smallest != i) { int temp = heap[i]; heap[i] = heap[smallest]; heap[smallest] = temp; i = smallest; } else { break; } } } System.out.println(java.util.Arrays.toString(java.util.Arrays.copyOf(heap, size)));
First extract-min removes 2, replaces root with 5, bubble down results in [3,4,5,7,6]. Second extract-min removes 3, replaces root with 6, bubble down results in [4,6,5,7].
