1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5typedef struct MinHeap {
6int *arr;
7int size;
8int capacity;
9} MinHeap;
10
11MinHeap* createMinHeap(int capacity) {
12MinHeap* heap = (MinHeap*)malloc(sizeof(MinHeap));
13heap->capacity = capacity;
14heap->size = 0;
15heap->arr = (int*)malloc(capacity * sizeof(int));
16return heap;
17}
18
19int parent(int i) { return (i - 1) / 2; }
20int left(int i) { return 2 * i + 1; }
21int right(int i) { return 2 * i + 2; }
22
23void swap(int *a, int *b) {
24int temp = *a;
25*a = *b;
26*b = temp;
27}
28
29void bubbleUp(MinHeap* heap, int index) {
30while (index > 0 && heap->arr[parent(index)] > heap->arr[index]) {
31swap(&heap->arr[parent(index)], &heap->arr[index]);
32index = parent(index);
33}
34}
35
36void bubbleDown(MinHeap* heap, int index) {
37int smallest = index;
38int l = left(index);
39int r = right(index);
40
41if (l < heap->size && heap->arr[l] < heap->arr[smallest])
42smallest = l;
43if (r < heap->size && heap->arr[r] < heap->arr[smallest])
44smallest = r;
45
46if (smallest != index) {
47swap(&heap->arr[index], &heap->arr[smallest]);
48bubbleDown(heap, smallest);
49}
50}
51
52void insert(MinHeap* heap, int value) {
53if (heap->size == heap->capacity) {
54printf("Heap is full\n");
55return;
56}
57heap->arr[heap->size] = value;
58bubbleUp(heap, heap->size);
59heap->size++;
60printf("%d inserted\n", value);
61}
62
63int extractMin(MinHeap* heap) {
64if (heap->size == 0) {
65printf("Heap is empty\n");
66return -1;
67}
68int root = heap->arr[0];
69heap->arr[0] = heap->arr[heap->size - 1];
70heap->size--;
71bubbleDown(heap, 0);
72return root;
73}
74
75int getMin(MinHeap* heap) {
76if (heap->size == 0) return -1;
77return heap->arr[0];
78}
79
80int main() {
81MinHeap* heap = createMinHeap(100);
82insert(heap, 10);
83insert(heap, 5);
84insert(heap, 20);
85insert(heap, 2);
86printf("Min: %d\n", getMin(heap));
87printf("Extracted: %d\n", extractMin(heap));
88return 0;
89}