|
| 1 | +#include<stdio.h> |
| 2 | +#include<limits.h> |
| 3 | + |
| 4 | +/*Declaring heap globally so that we do not need to pass it as an argument every time*/ |
| 5 | +/* Heap implemented here is Min Heap */ |
| 6 | + |
| 7 | +int heap[1000000], heapSize; |
| 8 | +/*Initialize Heap*/ |
| 9 | +void Init() { |
| 10 | + heapSize = 0; |
| 11 | + heap[0] = -INT_MAX; |
| 12 | +} |
| 13 | + |
| 14 | +/*Insert an element into the heap */ |
| 15 | +void Insert(int element) { |
| 16 | + heapSize++; |
| 17 | + heap[heapSize] = element; /*Insert in the last place*/ |
| 18 | + /*Adjust its position*/ |
| 19 | + int now = heapSize; |
| 20 | + while (heap[now / 2] > element) { |
| 21 | + heap[now] = heap[now / 2]; |
| 22 | + now /= 2; |
| 23 | + } |
| 24 | + heap[now] = element; |
| 25 | +} |
| 26 | + |
| 27 | +int DeleteMin() { |
| 28 | + |
| 29 | + lastElement = heap[heapSize--]; |
| 30 | + |
| 31 | + for (now = 1; now * 2 <= heapSize; now = child) { |
| 32 | + |
| 33 | + child = now * 2; |
| 34 | + |
| 35 | + if (child != heapSize && heap[child + 1] < heap[child]) { |
| 36 | + child++; |
| 37 | + } |
| 38 | + |
| 39 | + if (lastElement > heap[child]) { |
| 40 | + heap[now] = heap[child]; |
| 41 | + } else /* It fits there */ |
| 42 | + { |
| 43 | + break; |
| 44 | + } |
| 45 | + } |
| 46 | + heap[now] = lastElement; |
| 47 | + return minElement; |
| 48 | +} |
| 49 | + |
| 50 | +int main() { |
| 51 | + int number_of_elements; |
| 52 | + printf("Program to demonstrate Heap:\nEnter the number of elements: "); |
| 53 | + scanf("%d", &number_of_elements); |
| 54 | + int iter, element; |
| 55 | + Init(); |
| 56 | + printf("Enter the elements: "); |
| 57 | + for (iter = 0; iter < number_of_elements; iter++) { |
| 58 | + scanf("%d", &element); |
| 59 | + Insert(element); |
| 60 | + } |
| 61 | + for (iter = 0; iter < number_of_elements; iter++) { |
| 62 | + printf("%d ", DeleteMin()); |
| 63 | + } |
| 64 | + printf("\n"); |
| 65 | + return 0; |
| 66 | +} |
0 commit comments