MIT-Curricular/DS/C/endsem-omnibus/heap.c

126 lines
2.3 KiB
C
Raw Normal View History

2024-11-20 08:29:16 +05:30
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// Structure for Min Heap
typedef struct {
int arr[MAX_SIZE];
int size;
} MinHeap;
// Structure for Stack
typedef struct {
int arr[MAX_SIZE];
int top;
} Stack;
// Initialize empty stack
void initStack(Stack *s) {
s->top = -1;
}
// Check if stack is empty
int isEmpty(Stack *s) {
return s->top == -1;
}
// Check if stack is full
int isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
// Push element onto stack
void push(Stack *s, int value) {
if(isFull(s)) {
printf("Stack Overflow\n");
return;
}
s->arr[++s->top] = value;
}
// Pop element from stack
int pop(Stack *s) {
if(isEmpty(s)) {
printf("Stack Underflow\n");
return -1;
}
return s->arr[s->top--];
}
// Initialize Min Heap
void initMinHeap(MinHeap *heap) {
heap->size = 0;
}
// Helper function to swap elements
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Heapify function
void heapify(MinHeap *heap, int index) {
int smallest = index;
int left = 2 * index + 1;
int right = 2 * index + 2;
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 != index) {
swap(&heap->arr[index], &heap->arr[smallest]);
heapify(heap, smallest);
}
}
// Convert stack to min heap
void stackToHeap(Stack *s, MinHeap *heap) {
// Copy stack elements to heap array
heap->size = s->top + 1;
for(int i = 0; i <= s->top; i++) {
heap->arr[i] = s->arr[i];
}
// Heapify all non-leaf nodes
for(int i = (heap->size/2) - 1; i >= 0; i--) {
heapify(heap, i);
}
}
int main() {
Stack stack;
MinHeap heap;
initStack(&stack);
initMinHeap(&heap);
// Push some elements onto stack
push(&stack, 5);
push(&stack, 3);
push(&stack, 8);
push(&stack, 1);
push(&stack, 2);
printf("Original Stack: ");
for(int i = 0; i <= stack.top; i++) {
printf("%d ", stack.arr[i]);
}
printf("\n");
// Convert stack to min heap
stackToHeap(&stack, &heap);
printf("After Heapifying: ");
for(int i = 0; i < heap.size; i++) {
printf("%d ", heap.arr[i]);
}
printf("\n");
return 0;
}