#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void heapify(int arr[], int n, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left child index
int right = 2 * i + 2; // right child index
if (left < n && arr[left] > arr[largest])
largest = left; // left child is larger
if (right < n && arr[right] > arr[largest])
largest = right; // right child is larger
if (largest != i) {
swap(&arr[i], &arr[largest]); // swap root with largest child
heapify(arr, n, largest); // recursively heapify affected subtree
}
}
void buildHeap(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i); // heapify from last non-leaf to root
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d", arr[i]);
if (i != n - 1) printf(", ");
}
printf("\n");
}
int main() {
int arr[] = {4, 10, 3, 5, 1};
int n = sizeof(arr) / sizeof(arr[0]);
buildHeap(arr, n);
printArray(arr, n);
return 0;
}
if (left < n && arr[left] > arr[largest])
largest = left;
Check if left child is larger than current largest
if (right < n && arr[right] > arr[largest])
largest = right;
Check if right child is larger than current largest
if (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
Swap root with largest child and heapify subtree recursively
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
Build heap by heapifying all non-leaf nodes bottom-up