Example 1 — Max heap from five values
Pops come out sorted descending.
#include <stdio.h>
static void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }
static void push(int h[], int *n, int v) {
int i = (*n)++;
h[i] = v;
while (i > 0 && h[(i - 1) / 2] < h[i]) {
swap(&h[(i - 1) / 2], &h[i]);
i = (i - 1) / 2;
}
}
static int pop(int h[], int *n) {
int top = h[0];
h[0] = h[--(*n)];
int i = 0;
for (;;) {
int l = 2 * i + 1, r = l + 1, s = i;
if (l < *n && h[l] > h[s]) s = l;
if (r < *n && h[r] > h[s]) s = r;
if (s == i) break;
swap(&h[i], &h[s]);
i = s;
}
return top;
}
int main(void) {
int h[16], n = 0;
int in[] = {5, 3, 8, 1, 4};
for (int i = 0; i < 5; i++) push(h, &n, in[i]);
printf("heap array:");
for (int i = 0; i < n; i++) printf(" %d", h[i]);
printf("\nextracted:");
while (n > 0) printf(" %d", pop(h, &n));
printf("\n");
return 0;
} How It Works
- Pushing 8 sifts it above 5; pushing 4 sifts it above 3.
- The root 8 is the maximum.
- Pops return values in descending order.
