All pages 7 of 8

The heap

A ladder of matches where the smaller number always wins, so the smallest of all waits at the top.

1385413854
In life: The winner is always at the top.
0123456789101112131434853485
The smallest, 1, is out in 3 steps.

Counted: 3 steps

Work the machine

The steps

  1. Take 1, the smallest, off the top.
  2. Move 4, from the last box, to the top.
  3. 4 is bigger than 3, the smaller of its children, 3 and 8, so they swap.
  4. 4 is not bigger than 5, its only child, so it stays.
  5. The smallest, 1, is out in 3 steps.
The machine, at the end of the worked example. Press a button to make a move and watch it, one step at a time.
find: about the same, whatever the size1 stepadd: a few4 stepsremove: a few4 steps
The costs, with 8 things inside, counted by running the machine above: one box a step.

What it is

Picture a ladder of matches in a game. In each match the smaller number wins and moves up. Whoever is at the top has beaten everyone, so the smallest number is always there.

This is called a heap. Each node is no bigger than its children. Nothing else about the order is fixed, which is what makes a heap quick to keep.

How a move works

The ladder is really a row of boxes. The children of box 0 are boxes 1 and 2. The children of box 1 are boxes 3 and 4.

Add 5, 3, 8, 1 and 4. Each new number goes in the first free box. Then it swaps with the box above it for as long as it is smaller. When 1 lands in box 3, it beats 5 and then 3, and climbs to the top. The row reads 1, 3, 8, 5, 4.

To take the smallest, take 1 off the top. Move the last box, 4, up to the top. 4 is bigger than its smaller child, 3, so they swap. The row reads 3, 4, 8, 5. That is 3 steps.

Where you meet it

Heaps choose what comes next. A list at a hospital that sees the most urgent case first can be a heap. So can a game that runs the next timer, or a map app that tries the nearest road first.

Watch out for

The row is the tree. The children of box i are boxes 2i+1 and 2i+2, so no arrows are kept. But only the top is easy to find. Looking for any other number means checking the whole row.