#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void bubbleDown(int heap[], int size, int index) {
int smallest = index;
int left = 2 * index + 1;
int right = 2 * index + 2;
// Check if left child exists and is smaller
if (left < size && heap[left] < heap[smallest]) {
smallest = left;
}
// Check if right child exists and is smaller
if (right < size && heap[right] < heap[smallest]) {
smallest = right;
}
// If smallest is not current index, swap and continue bubbling down
if (smallest != index) {
swap(&heap[index], &heap[smallest]);
bubbleDown(heap, size, smallest); // recursive call
}
}
int extractMin(int heap[], int *size) {
if (*size <= 0) {
return -1; // empty heap
}
int root = heap[0];
heap[0] = heap[*size - 1]; // move last element to root
(*size)--;
bubbleDown(heap, *size, 0); // restore heap property
return root;
}
void printHeap(int heap[], int size) {
for (int i = 0; i < size; i++) {
printf("%d", heap[i]);
if (i != size - 1) {
printf(" -> ");
}
}
printf(" -> null\n");
}
int main() {
int heap[] = {10, 15, 20, 30, 40, 50, 60};
int size = 7;
printf("Original heap:\n");
printHeap(heap, size);
int min = extractMin(heap, &size);
printf("Extracted min: %d\n", min);
printf("Heap after extractMin and bubble down:\n");
printHeap(heap, size);
return 0;
}
heap[0] = heap[*size - 1]; // move last element to root
Replace root with last element to maintain complete tree shape
Reduce heap size after removing root
bubbleDown(heap, *size, 0); // restore heap property
Push down the new root to correct position to restore min-heap
if (left < size && heap[left] < heap[smallest]) { smallest = left; }
Find smaller child to swap with
if (right < size && heap[right] < heap[smallest]) { smallest = right; }
Check right child for smaller value
if (smallest != index) { swap(&heap[index], &heap[smallest]); bubbleDown(heap, size, smallest); }
Swap with smaller child and continue bubbling down recursively
Original heap:
10 -> 15 -> 20 -> 30 -> 40 -> 50 -> 60 -> null
Extracted min: 10
Heap after extractMin and bubble down:
15 -> 30 -> 20 -> 60 -> 40 -> 50 -> null