Example 1 — Build a max heap in place
Input: 4, 10, 3, 5, 1.
#include <stdio.h>
static void heapify(int a[], int n, int i) {
for (;;) {
int l = 2 * i + 1, r = l + 1, s = i;
if (l < n && a[l] > a[s]) s = l;
if (r < n && a[r] > a[s]) s = r;
if (s == i) return;
int t = a[i]; a[i] = a[s]; a[s] = t;
i = s;
}
}
int main(void) {
int a[] = {4, 10, 3, 5, 1};
int n = 5;
printf("input:");
for (int i = 0; i < n; i++) printf(" %d", a[i]);
for (int i = n / 2 - 1; i >= 0; i--) heapify(a, n, i);
printf("\nmax-heap:");
for (int i = 0; i < n; i++) printf(" %d", a[i]);
printf("\n");
return 0;
} How It Works
- The last parent is index 1 (10); it is already larger than 5 and 1.
- At index 0, 4 swaps with 10, then with 5.
- The final array is a valid max heap.
