Heap Insertion in C

Intermediate
6 min read
Updated: Nov 2026
1 example

Sift Up

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;
}

Cheat Sheet

Keep these facts handy while you work with Heap Insertion in C in C.

TopicDetail
Step 1Append at the end
Step 2Swap with parent while out of order
SwapsAt most log n
TimeO(log n)

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;
}

How It Works

  1. 45 lands at index 5 whose parent (index 2) holds 40.
  2. It is larger, so it swaps upward once.
  3. 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.

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.

Next: Heap Deletion in C

Remove the root, move the last element up, and sift it down.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful