This is where we go from O(n²) sorting and list-based priority queues to the O(log n) power of the heap.
A Binary Heap is:
It’s used mainly for:
A complete binary tree is one that grows in breadth-first order:
Level 0: 1
Level 1: 2 3
Level 2: 4 5 6 7
Level 3: 8 9 10 11 12 13 14 15
Each new node fills from left to right before starting a new level.
This property makes the heap easy to store in an array rather than in explicit node objects:
| Tree node | Array index |
|---|---|
| root | 1 (or 0) |
| left child of i | 2 × i |
| right child of i | 2 × i + 1 |
| parent of i | ⌊ i / 2 ⌋ |