Data Structures & Algorithms / Module 0: Thinking in cost
Topic 0.1
Algorithms, steps and input size
An algorithm is a step-by-step recipe, and its weight is measured in steps against the size of the input.
Watch: the number in the bottom-right corner goes up by one every time a number is compared. A longer list means more steps.
- moving now
- being checked
- passed / marked
- finished / the result
- no longer used
A recipe, not magic
Finding the largest number in a list can be written as a recipe anyone could follow, even without a computer:
- Treat the first number as the largest.
- Look at the next number. If it is bigger, remember it as the largest.
- Repeat until every number has been seen.
That is an algorithm. A computer just follows those steps very quickly. Press Step in the figure to watch each one.
Steps and input size
What matters isn't how many seconds the algorithm runs, because that depends on the computer. What matters is how many steps it needs for an input of a given size. The input size is usually written as n: how many numbers are in the list, how many users, how many rows in the table.
Switch lists in the figure. 3 numbers need 2 comparisons, 8 numbers need 7, 12 numbers need 11. The pattern: n numbers need n − 1 comparisons. A list twice as long means roughly twice the work.
Code, for programmersThe same recipe in code
function largest(list) {
let best = list[0]; // step 1: the first one
for (let i = 1; i < list.length; i++) {
if (list[i] > best) best = list[i]; // step 2: bigger? remember it
}
return best; // step 3: every number seen
}Quiz
To find the largest number in a list of 100 numbers, how many comparisons does the recipe above need?
What does n mean when talking about algorithms?
The code above is given an empty list. What happens?
0 of 3 answered.
Built on
No prerequisites.