C Binary Heap Representation

Intermediate
6 min read
Updated: Nov 2026
1 example

Heap as an Array

Because the tree is complete, it packs into an array with no gaps. For 0-based index i: left child 2i + 1, right child 2i + 2, parent (i - 1) / 2. A node has a left child only if 2i + 1 < n, and a right child only if 2i + 2 < n.

Remember
left   = 2 * i + 1;      /* valid if < n */
right  = 2 * i + 2;      /* valid if < n */
parent = (i - 1) / 2;    /* for i > 0   */

Cheat Sheet

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

TopicDetail
Left2i + 1
Right2i + 2
Parent(i - 1) / 2
Last parentn / 2 - 1

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Min Heap in C.

Example 1 — Print children by index

Show each parent with its children, or "none".

C
#include <stdio.h>

int main(void) {
    int a[] = {2, 5, 3, 9, 6, 4};
    int n = 6;

    for (int i = 0; i < 3; i++) {
        int l = 2 * i + 1, r = 2 * i + 2;
        printf("index %d: value %d, left ", i, a[i]);
        if (l < n) printf("%d", a[l]); else printf("none");
        printf(", right ");
        if (r < n) printf("%d", a[r]); else printf("none");
        printf("\n");
    }
    return 0;
}

How It Works

  1. Index 2 has a left child at index 5 (value 4).
  2. Its right child would be index 6, which is not less than 6, so it prints "none".
  3. Always bounds-check child indexes against n.

Edge Cases & Pitfalls

Check these before relying on Binary Heap Representation in real programs.

bound

Missing bounds checks

Reading a[2*i+1] without checking < n reads past the heap.

base

Off-by-one with 1-based

In 1-based arrays use 2i, 2i+1, and i/2.

Key Takeaways

  • No pointers needed.
  • Check against n.
  • Last parent is n/2 - 1.

One line: Because the tree is complete, it packs into an array with no gaps.

Frequently Asked Questions

For 0-based index i: parent is (i-1)/2, left child is 2i+1, right child is 2i+2.
Because it is a complete binary tree, so there are no gaps in the level-order layout.
Continue with "Min Heap in C" next. Implement push and pop for a min heap with sift-up and sift-down. The C Heaps hub lists every topic in order.

Next: Min Heap in C

Implement push and pop for a min heap with sift-up and sift-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.

9 people found this page helpful