LOGBOOK

HELP

Quiz Entry - updated: 2026.12.01

How is a heap stored in an array, and how are a node's children, its parent, the last node and the insertion position found?

Store the nodes in level order starting at index 1: the node at index i has its children at 2i and 2i + 1 and its parent at ⌊i/2⌋. With n entries the last node is at index n, and a new entry goes to index n + 1.

The heap 1, 2, 4, 5, 3 drawn as a tree with yellow index numbers and as the array slots 1 to 5, slot 6 dashed

* Level order fills the array without gaps, so parent and child positions are pure index arithmetic. *

Because a heap is a complete binary tree, its level order has no gaps, so the array is filled contiguously from index 1 to n (index 0 is left empty so that the arithmetic stays simple):

Wanted Index
root 1
left child of i 2i
right child of i 2i + 1
parent of i ⌊i/2⌋ (integer division)
last node n
insertion position n + 1

For the heap 1 → (2, 4), 2 → (5, 3), the array is [–, 1, 2, 4, 5, 3]: the children of 2 (index 2) are at indices 4 and 5, namely 5 and 3; the parent of 3 (index 5) is at index 2.

This is why array-based heaps are the standard implementation. Finding the insertion node, the last node, a parent or a child is pure index arithmetic, $O(1)$, with no pointers to follow. Upheap is "swap with index i/2", downheap is "swap with index 2i or 2i + 1". The flip side: a fixed-size array can fill up, so it either has a capacity limit or must grow like a dynamic array.

Tip: with 0-based indexing the formulas shift to children 2i + 1 and 2i + 2 and parent ⌊(i − 1)/2⌋. Both conventions are common; check which one a codebase uses.

Go deeper:

From Quiz: ADS / Priority Queues and Heaps | Updated: Dec 01, 2026