The biggest, without sorting
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.
- 55 > 43, so best becomes 55.
- 78 > 55, so best becomes 78.
- 62 is not > 78. Best stays 78.
- 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.