Data Structures & Algorithms / Module 0: Thinking in cost

Topic 0.3

Best, average and worst case

The same algorithm can be fast or slow depending on the data, and why the worst case is usually what counts.

7 min · beginner

Watch: choose where the number you're looking for sits. At the front it's found at once; at the back, or missing, it takes every step.

0123456712317254018933
  • moving now
  • being checked
  • finished / the result
  • no longer used
Step 1 of 6

Look for 40, left to right.

The algorithm is the same, but the number of steps depends on where the target is: 1 step at the front, 8 at the back or when it's missing.
find:

Like looking for keys in a drawer

You open drawers one by one looking for your keys. If they are in the first drawer, you're done in one step. If they are in the last one, or in none at all, every drawer gets opened. The method is exactly the same; only where the keys are changes.

Pick different targets in the figure and count the steps:

  • Best case: the target is first. 1 step.
  • Average case: the target is somewhere random. About half the list, on average.
  • Worst case: the target is last or missing. All n steps.

Why we plan for the worst case

The best case sounds nice, but you can't rely on it. Users will search for things that aren't there, data will arrive in odd orders, and if one request in a thousand hits the worst case, your server still has to handle it. So when people say "linear search is O(n)", they mean: in the worst case, its steps grow in proportion to n.

Code, for programmersLinear search: fast or slow depending on where the target is
function find(list, target) {
  for (let i = 0; i < list.length; i++) {
    if (list[i] === target) return i;   // best case: stops at i = 0
  }
  return -1;                            // worst case: checked everything
}

Quiz

  1. Linear search on 1,000 items. How many steps in the worst case?

  2. Why do we usually plan for the worst case?

  3. On average, how many steps does linear search take on 1,000 items if the target is always there, at a random position?

0 of 3 answered.