PUE Assignment - 3
PUE Assignment - 3
radixSort(arr, n);
return 0;
}
Output :--
Build Min heap using top down approach :--
#include <stdio.h>
#include <stdlib.h>
// Function to swap two elements
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void heapify(int heap[], int i, int n) {
int smallest = i; // Initialize the smallest element as root
int left = 2 * i + 1; // Left child index
int right = 2 * i + 2; // Right child index
if (left < n && heap[left] < heap[smallest]) {
smallest = left;
}
if (right < n && heap[right] < heap[smallest]) {
smallest = right;
}
if (smallest != i) {
swap(&heap[i], &heap[smallest]);
heapify(heap, smallest, n);
}
}
void insertMinHeap(int heap[], int* n, int value) {
// Increase the size of the heap
(*n)++;
int i = *n - 1;
heap[i] = value;
while (i != 0 && heap[(i - 1) / 2] > heap[i]) {
swap(&heap[i], &heap[(i - 1) / 2]);
i = (i - 1) / 2;
}
}
void buildMinHeap(int heap[], int n) {
// Start with the first non-leaf node and heapify all nodes
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(heap, i, n);
}
}
void printHeap(int heap[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", heap[i]);
}
printf("\n");
}
int main() {
int heap[10];
int n = 0; // Initial size of the heap is 0
insertMinHeap(heap, &n, 10);
insertMinHeap(heap, &n, 20);
insertMinHeap(heap, &n, 5);
insertMinHeap(heap, &n, 30);
insertMinHeap(heap, &n, 40);
insertMinHeap(heap, &n, 15);
printf("Min-Heap after insertions (Top-Down approach): ");
printHeap(heap, n);