#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Heapify for min heap
void minHeapify(int arr[], int n, int i) {
int smallest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] < arr[smallest])
smallest = left;
if (right < n && arr[right] < arr[smallest])
smallest = right;
if (smallest != i) {
swap(&arr[i], &arr[smallest]);
minHeapify(arr, n, smallest); // recurse to fix subtree
}
}
// Heapify for max heap
void maxHeapify(int arr[], int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(&arr[i], &arr[largest]);
maxHeapify(arr, n, largest); // recurse to fix subtree
}
}
void buildMinHeap(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--) {
minHeapify(arr, n, i); // fix heap from bottom up
}
}
void buildMaxHeap(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--) {
maxHeapify(arr, n, i); // fix heap from bottom up
}
}
void printHeap(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {5, 3, 8, 1, 6};
int n = sizeof(arr) / sizeof(arr[0]);
int minHeap[n];
int maxHeap[n];
// Copy original array to both heaps
for (int i = 0; i < n; i++) {
minHeap[i] = arr[i];
maxHeap[i] = arr[i];
}
buildMinHeap(minHeap, n);
buildMaxHeap(maxHeap, n);
printf("Min Heap: ");
printHeap(minHeap, n);
printf("Max Heap: ");
printHeap(maxHeap, n);
return 0;
}
if (left < n && arr[left] < arr[smallest])
smallest = left;
compare left child to current smallest to find min
if (right < n && arr[right] < arr[smallest])
smallest = right;
compare right child to current smallest to find min
if (smallest != i) {
swap(&arr[i], &arr[smallest]);
minHeapify(arr, n, smallest);
swap to fix min heap property and recurse to fix subtree
if (left < n && arr[left] > arr[largest])
largest = left;
compare left child to current largest to find max
if (right < n && arr[right] > arr[largest])
largest = right;
compare right child to current largest to find max
if (largest != i) {
swap(&arr[i], &arr[largest]);
maxHeapify(arr, n, largest);
swap to fix max heap property and recurse to fix subtree
for (int i = n / 2 - 1; i >= 0; i--) {
minHeapify(arr, n, i);
build min heap from bottom up
for (int i = n / 2 - 1; i >= 0; i--) {
maxHeapify(arr, n, i);
build max heap from bottom up
Min Heap: 1 3 8 5 6
Max Heap: 8 6 5 1 3