#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 heapSort(int arr[], int n) {
// Build max heap
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i); // heapify from bottom up
}
// Extract elements from heap one by one
for (int i = n - 1; i > 0; i--) {
swap(&arr[0], &arr[i]); // move current root to end
heapify(arr, i, 0); // heapify reduced heap
}
}
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]);
printf("Original array:\n");
printArray(arr, n);
heapSort(arr, n);
printf("Sorted array:\n");
printArray(arr, n);
return 0;
}
for (int i = n / 2 - 1; i >= 0; i--) { heapify(arr, n, i); }
build max heap from bottom non-leaf nodes up
for (int i = n - 1; i > 0; i--) { swap(&arr[0], &arr[i]); heapify(arr, i, 0); }
extract max element to end and restore heap
if (largest != i) { swap(&arr[i], &arr[largest]); heapify(arr, n, largest); }
swap root with largest child and heapify subtree
Original array:
4 -> 10 -> 3 -> 5 -> 1
Sorted array:
1 -> 3 -> 4 -> 5 -> 10