A heap satisfies two rules: it is a complete binary tree (all levels full except possibly the last, filled left to right) and it obeys the heap property (each parent compares favorably with its children). The name is unrelated to the dynamic memory heap used by malloc.
#include <stdio.h>
int main(void) {
int a[] = {2, 5, 3, 9, 6, 4};
int n = 6, ok = 1;
for (int i = 1; i < n; i++) {
if (a[(i - 1) / 2] > a[i]) {
printf("violation at index %d\n", i);
ok = 0;
}
}
printf("valid min-heap: %s\n", ok ? "yes" : "no");
return 0;
}
Output
valid min-heap: yes
How It Works
Index 1 and 2 have parent 2, which is smaller.
Index 3 and 4 have parent 5; index 5 has parent 3.
No parent is larger than a child, so the heap is valid.
Edge Cases & Pitfalls
Check these before relying on Heap Basics in real programs.
name
Confusing with malloc heap
Both are called "heap" but they are unrelated.
shape
Breaking completeness
Insert at the next free array slot to keep the shape.
Remember
Key Takeaways
Complete tree plus order.
Root is the min or max.
Not fully sorted.
One line: A heap satisfies two rules: it is a complete binary tree (all levels full except possibly the last, filled left to right) and it obeys the heap property (each parent compares favorably with its children).
Frequently Asked Questions
No. The heap data structure is a tree-based structure; heap memory is the region used for dynamic allocation.
No. Only the parent-child ordering holds; the array is not fully sorted.
Continue with "C Binary Heap Representation" next. Use index arithmetic to find parents and children without pointers. The C Heaps hub lists every topic in order.