In a min heap each parent is less than or equal to its children, so the minimum is always h[0]. Push appends at the end and sifts up while smaller than the parent. Pop takes the root, moves the last element to the root, and sifts down by swapping with the smaller child.
Remember
push: h[n++] = v; while (h[parent] > h[i]) swap, i = parent;
pop : top = h[0]; h[0] = h[--n]; sift down to smaller child;
Reference
Cheat Sheet
Keep these facts handy while you work with Min Heap in C in C.
Topic
Detail
Peek min
O(1)
Push
O(log n)
Pop min
O(log n)
Sift down
Swap with the smaller child
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Max Heap in C.
Example 1 — Push five values and pop them in order
Pops come out sorted ascending.
C
#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;
}
Output
heap array: 1 3 8 5 4
extracted: 1 3 4 5 8
How It Works
Pushing 1 sifts it up to the root through 5 and 3.
The array is a valid heap but not sorted.
Repeated pops return the smallest remaining value each time.
Edge Cases & Pitfalls
Check these before relying on Min Heap in C in real programs.
empty
Pop on empty heap
Check n > 0 before popping.
child
Swapping with the wrong child
In a min heap swap with the smaller child.
Remember
Key Takeaways
Root is the minimum.
Sift up on push.
Sift down on pop.
One line: In a min heap each parent is less than or equal to its children, so the minimum is always h[0].
Frequently Asked Questions
A heap where every parent is less than or equal to its children, so the smallest element is at the root.
Peek O(1); push and pop O(log n).
Continue with "Max Heap in C" next. Implement a max heap by flipping the comparisons of a min heap. The C Heaps hub lists every topic in order.