To insert, place the new value in the next free array slot (keeping the tree complete), then sift up: while it is larger than its parent (max heap), swap with the parent. At most log n swaps are needed, so insertion is O(log n).
Remember
h[n] = v; i = n; n++;
while (i > 0 && h[(i - 1) / 2] < h[i]) {
swap(&h[(i - 1) / 2], &h[i]);
i = (i - 1) / 2;
}
Reference
Cheat Sheet
Keep these facts handy while you work with Heap Insertion in C in C.
Topic
Detail
Step 1
Append at the end
Step 2
Swap with parent while out of order
Swaps
At most log n
Time
O(log n)
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Heap Deletion in C.
Example 1 — Insert 45 into a max heap
Start from 50, 30, 40, 10, 20.
C
#include <stdio.h>
int main(void) {
int h[8] = {50, 30, 40, 10, 20};
int n = 5;
h[n] = 45;
int i = n++;
while (i > 0) {
int p = (i - 1) / 2;
if (h[p] >= h[i]) break;
printf("swap %d with %d\n", h[i], h[p]);
int t = h[p]; h[p] = h[i]; h[i] = t;
i = p;
}
printf("heap:");
for (int k = 0; k < n; k++) printf(" %d", h[k]);
printf("\n");
return 0;
}
Output
swap 45 with 40
heap: 50 30 45 10 20 40
How It Works
45 lands at index 5 whose parent (index 2) holds 40.
It is larger, so it swaps upward once.
Its new parent is 50, which is larger, so it stops.
Edge Cases & Pitfalls
Check these before relying on Heap Insertion in C in real programs.
full
Array capacity
Check n < capacity before inserting.
order
Incrementing n too early or late
Use the index of the new slot, then increase n.
Remember
Key Takeaways
Append then sift up.
O(log n).
Stops when parent is larger.
One line: To insert, place the new value in the next free array slot (keeping the tree complete), then sift up: while it is larger than its parent (max heap), swap with the parent.
Frequently Asked Questions
Append the value at the end of the array and swap it upward with its parent until the heap property is restored.
O(log n) in the worst case.
Continue with "Heap Deletion in C" next. Remove the root, move the last element up, and sift it down. The C Heaps hub lists every topic in order.