Heapify (sift-down) restores the heap property at index i, assuming both child subtrees are already heaps. It swaps i with its larger child (max heap) and repeats on that child until the node is in place. It takes O(log n) and is the building block of both extraction and heap construction.
Remember
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;
swap(&a[i], &a[s]);
i = s;
}
}
Reference
Cheat Sheet
Keep these facts handy while you work with Heapify in C in C.
Topic
Detail
Precondition
Child subtrees are heaps
Action
Sift node i down
Time
O(log n)
Used by
Delete and build heap
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Building a Heap in C.
Example 1 — Heapify the root
Only the root, 3, violates the max-heap property.
C
#include <stdio.h>
static void show(const char *label, const int a[], int n) {
printf("%s:", label);
for (int i = 0; i < n; i++) printf(" %d", a[i]);
printf("\n");
}
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[] = {3, 9, 8, 7, 6, 5, 4};
show("before", a, 7);
heapify(a, 7, 0);
show("after heapify(0)", a, 7);
return 0;
}
At index 1 its children are 7 and 6, so it swaps with 7.
At index 3 there are no children; the heap is restored.
Edge Cases & Pitfalls
Check these before relying on Heapify in C in real programs.
pre
Violated precondition
If subtrees are not heaps, one pass will not fix the whole array.
bound
Child bounds
Always test l < n and r < n.
Remember
Key Takeaways
Local repair.
Needs valid subtrees.
O(log n).
One line: Heapify (sift-down) restores the heap property at index i, assuming both child subtrees are already heaps.
Frequently Asked Questions
It moves a node down the tree until the subtree rooted at it satisfies the heap property.
Yes, heapify usually refers to the sift-down procedure.
Continue with "Building a Heap in C" next. Turn an arbitrary array into a heap in O(n) by heapifying from the last parent. The C Heaps hub lists every topic in order.