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.

7 min · beginner

Watch: the number in the bottom-right corner goes up by one every time a number is compared. A longer list means more steps.

01234567492max75183
  • moving now
  • being checked
  • passed / marked
  • finished / the result
  • no longer used
Step 1 of 9

Start: assume the first number (4) is the largest.

PointerNumbers not checked yetEvery number is compared once with the largest so far. The number of steps grows with the length of the list.
list:

A recipe, not magic

Finding the largest number in a list can be written as a recipe anyone could follow, even without a computer:

  1. Treat the first number as the largest.
  2. Look at the next number. If it is bigger, remember it as the largest.
  3. 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

  1. To find the largest number in a list of 100 numbers, how many comparisons does the recipe above need?

  2. What does n mean when talking about algorithms?

  3. The code above is given an empty list. What happens?

0 of 3 answered.