Skip to content
Your progress

Checking your sign-in…

Who's learning?

Each profile keeps its own read lessons, badges, streak, and practice scores on this device.

Lesson 6 of 11

The biggest, without sorting

Show on a big screen

6 min

Text size

Five crates were unloaded from the lorry. They weigh 43, 55, 78, 62 and 31 kilograms. Which is the heaviest?

Loading lab…

Best starts at 43, the first crate.
Step 1 of 5
  1. Best starts at 43, the first crate.
  2. 55 > 43, so best becomes 55.
  3. 78 > 55, so best becomes 78.
  4. 62 is not > 78. Best stays 78.
  5. 31 is not > 78. Best stays 78.

The rule

The 78 kg crate is the heaviest. The program visits each crate once, in order. That is a walk. The best so far is the heaviest crate seen up to now.

Walk the list once, carrying the best so far. The biggest is found, and nothing is put in order. Start the best box at the first item. Then compare every item against it.

  • let best = weights[0]; — start with the first crate.
  • if (weight > best) — the question for every crate: is this crate heavier? The sign > means is bigger than.
  • best = weight; — only when the answer is yes.
  • return best; — after the last crate.

The biggest is what the best box holds at the end. For the smallest, use < (is smaller than) in the question.

Start at the first item on purpose. The first crate may be the heaviest. A delivery can also hold just one crate.

Do not start at 0. That is the number 0, not position 0. A list of night temperatures can all be below 0. Then the answer would be 0, which is not in the list.

Try the lab to finish this lesson.