A heap is a specialized tree-based data structure that satisfies the heap property. In a min-heap, for any given node I, the value of I is less than or equal to the values of its children. Heaps are commonly used to implement priority queues.
#include <stdio.h>#include <stdlib.h>#define MAX_SIZE 100struct MinHeap {int arr[MAX_SIZE];int size;};// Initialize heapvoid initHeap(struct MinHeap* heap) {heap->size = 0;}// Get parent indexint parent(int i) {return (i - 1) / 2;}// Get left child indexint leftChild(int i) {return 2 * i + 1;}// Get right child indexint rightChild(int i) {return 2 * i + 2;}// Get minimum elementint getMin(struct MinHeap* heap) {if (heap->size <= 0) {printf("Heap is empty\n");return -1;}return heap->arr[0];}// Insert new elementvoid insert(struct MinHeap* heap, int value) {if (heap->size >= MAX_SIZE) {printf("Heap is full\n");return;}// Insert at endint i = heap->size;heap->arr[i] = value;heap->size++;// Heapify upwhile (i != 0 && heap->arr[parent(i)] > heap->arr[i]) {// Swap with parentint temp = heap->arr[i];heap->arr[i] = heap->arr[parent(i)];heap->arr[parent(i)] = temp;i = parent(i);}}// Extract minimum elementint extractMin(struct MinHeap* heap) {if (heap->size <= 0) {printf("Heap is empty\n");return -1;}if (heap->size == 1) {heap->size--;return heap->arr[0];}// Store min value and remove itint root = heap->arr[0];heap->arr[0] = heap->arr[heap->size - 1];heap->size--;// Heapify downint i = 0;while (true) {int smallest = i;int left = leftChild(i);int right = rightChild(i);if (left < heap->size && heap->arr[left] < heap->arr[smallest])smallest = left;if (right < heap->size && heap->arr[right] < heap->arr[smallest])smallest = right;if (smallest != i) {// Swap with smallest childint temp = heap->arr[i];heap->arr[i] = heap->arr[smallest];heap->arr[smallest] = temp;i = smallest;} else {break;}}return root;}// Print heap arrayvoid printHeap(struct MinHeap* heap) {printf("Heap array: ");for (int i = 0; i < heap->size; i++) {printf("%d ", heap->arr[i]);}printf("\n");}int main() {struct MinHeap heap;initHeap(&heap);// Insert some valuesprintf("Inserting values: 3, 2, 1, 7, 8, 4\n");insert(&heap, 3);printHeap(&heap);insert(&heap, 2);printHeap(&heap);insert(&heap, 1);printHeap(&heap);insert(&heap, 7);printHeap(&heap);insert(&heap, 8);printHeap(&heap);insert(&heap, 4);printHeap(&heap);// Extract minimum valuesprintf("\nExtracting minimum values:\n");for (int i = 0; i < 3; i++) {int min = extractMin(&heap);printf("Extracted min: %d\n", min);printHeap(&heap);}return 0;}
made by billy | source code | @b9llach