Deleting (extracting) the root works in three steps: save the root, move the last element to the root, shrink the heap, then sift down by swapping with the larger child (max heap) until the property holds. This keeps the tree complete and runs in O(log n).
Remember
top = h[0];
h[0] = h[--n];
/* sift down: swap with larger child while smaller */
Reference
Cheat Sheet
Keep these facts handy while you work with Heap Deletion in C in C.
Topic
Detail
Step 1
Save the root
Step 2
Move last element to root
Step 3
Sift down
Time
O(log n)
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Heapify in C.
Example 1 — Remove the maximum
Heap: 50, 30, 45, 10, 20, 40.
C
#include <stdio.h>
int main(void) {
int h[8] = {50, 30, 45, 10, 20, 40};
int n = 6;
int removed = h[0];
h[0] = h[--n];
printf("removed %d\n", removed);
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;
printf("swap %d with %d\n", h[i], h[s]);
int t = h[i]; h[i] = h[s]; h[s] = t;
i = s;
}
printf("heap:");
for (int k = 0; k < n; k++) printf(" %d", h[k]);
printf("\n");
return 0;
}
Output
removed 50
swap 40 with 45
heap: 45 30 40 10 20
How It Works
The last element 40 moves to the root and the size becomes 5.
Its children are 30 and 45; 45 is larger, so they swap.
At index 2 there are no children left, so sifting stops.
Edge Cases & Pitfalls
Check these before relying on Heap Deletion in C in real programs.
empty
Deleting from an empty heap
Check n > 0 first.
child
Swapping with the smaller child
In a max heap swap with the larger child.
Remember
Key Takeaways
Replace root with last.
Sift down.
O(log n).
One line: Deleting (extracting) the root works in three steps: save the root, move the last element to the root, shrink the heap, then sift down by swapping with the larger child (max heap) until the property holds.
Frequently Asked Questions
Replace the root with the last element, reduce the size, and sift it down to restore the heap property.
It keeps the tree complete, so the array stays gap-free.
Continue with "Heapify in C" next. Sift one node down so its subtree becomes a heap. The C Heaps hub lists every topic in order.