Practice question · Put in order
Order the steps of the algorithm that finds the largest value in a list.
- Look at the next element in the list
- Report best as the maximum
- If that element is greater than best, set best to it
- Repeat until no elements remain
- Set best equal to the first element of the list
Hints
- An algorithm must start from a definite state before it can compare anything.
- The comparison happens after you have an element in hand, and the report happens only once the list is exhausted.
Show the answer
- Set best equal to the first element of the list
- Look at the next element in the list
- If that element is greater than best, set best to it
- Repeat until no elements remain
- Report best as the maximum
Why
You must initialise before you can compare, compare before you can update, and exhaust the list before you can be sure. Starting best at zero instead of the first element is the usual bug, it fails on a list of negative numbers.
Practise Algorithms and Computational Thinking
The app has 6 more questions on this lesson, and keeps your place in the course. Mathematics I is free to start.
More questions on Algorithms and Computational Thinking
- A recipe is a precise sequence of steps and is not an algorithm in the strict sense. Which requirement does…
- Select every procedure below that FAILS to be a genuine algorithm.
- A specification says WHAT the answer must be; an algorithm says HOW to get it. Why is the distinction worth…
- An algorithm says HOW to compute; a specification says only WHAT the answer is. Sort each item.