1 of 4

Your RightSignal

Data structures · 7 of 111 / 3

Heaps

The concept

How a priority queue serves the most urgent job without sorting

A heap is a binary tree with one rule: every parent is smaller than or equal to its children. This version is called a min-heap. Because of the rule, the smallest item always sits at the top (the root), so you can read it in O(1) time.

Unlike ordered binary trees, a heap ignores how two siblings compare. For example, 2 on top with children 5 and 3, and 9 and 7 under the 5, is a valid heap: 2 leads, yet nothing is sorted. That looser rule keeps updates cheap.

A heap fills each level left to right before starting the next. A tree with no gaps like this is called complete, so it fits in a plain array with no pointers: the root goes at index 0, and the levels follow one after another.

What it’s forFinds an item's children and parent inside the array, so the tree needs no pointers.

children of i: 2i + 1 and 2i + 2; parent of i: ⌊(i − 1) / 2⌋

i
the item's position in the array, starting at 0 for the root
⌊ ⌋
round down to a whole number

What it givesWhere to look when an item has to move up or down the tree.

  1. Item at index 3 has children at 2·3+1 = 7 and 2·3+2 = 8
  2. Its parent is ⌊(3 − 1)/2⌋ = 1
  3. The root's children are at 2·0+1 = 1 and 2·0+2 = 2