What a heap is, and why it lives in an array
A weaker ordering than a BST, and index arithmetic instead of pointers.
A heap is a complete binary tree with one rule: every parent compares favourably to its children. In a min-heap, each parent is ≤ both children; in a max-heap, ≥.
Note what the rule does not say. Siblings have no relationship, and the tree is not sorted. That weaker promise is what makes a heap cheap to maintain — you only ever fix one root-to-leaf path.
1
/ \
3 2 A valid min-heap.
/ \ / 3 sits above 4 and 5; 2 above 6.
4 5 6 3 > 2 is fine — they are not on a path.
The array trick
Because the tree is complete — every level full except the last, filled left to right — it can live in a flat array with no pointers at all:
const parent = (i) => (i - 1) >> 1;
const left = (i) => 2 * i + 1;
const right = (i) => 2 * i + 2;
// The tree above, as an array:
const heap = [1, 3, 2, 4, 5, 6];
No node objects, no allocation per element, and perfect cache locality. This is the payoff for insisting the tree stays complete.
The costs
| Operation | Cost |
|---|---|
peek — smallest (or largest) |
O(1) |
push |
O(log n) |
pop |
O(log n) |
| Build from n items | O(n) |
| Search for an arbitrary value | O(n) |
That last row matters: a heap is not a search structure. If you need "is x present?", you need a different tool.
Building in O(n) rather than O(n log n) is a genuine result: heapifying bottom-up, most nodes are near the leaves and sink at most a level or two, and the sum converges to linear.
Heap versus BST
| Heap | Balanced BST | |
|---|---|---|
| Minimum | O(1) | O(log n) |
| Search | O(n) | O(log n) |
| Sorted iteration | O(n log n) | O(n) |
| Memory | Array, no pointers | Node per element |
Choose a heap when you only ever want the extreme element. Choose a BST when you need order or lookup. Most "top k" and scheduling problems only want the extreme — hence the heap's ubiquity.