Skip to content

best, worst and average cases

counting the cost

what it is

For one size of input, a method can cost different amounts. A case says which inputs you count, the cheapest, the dearest or the mean over many.

Take 'look at every name', from counting basic steps, on a list of 4 names. Its four instructions, A to D, stand in the table below. With the name wanted at place 1, it runs 3 instructions: A, B and C. Each place further on costs 3 more. With the name missing, it runs 14. One size, five kinds of list, five costs.

instructionwhat it does
Astart at place 1
Bif there is no name here, say the name is not there, and stop
Cif the name here is the one wanted, say where, and stop
Dmove on to the next place, and go back to B
The four instructions, from counting basic steps.
name at place 11234C stops it3 instructionsname at place 31234C stops it9 instructionsname missing1234B stops it14 instructionswhere it stopsnever looked atpast the end
Looking through 4 names from place 1. C stops at the name wanted, and B past the end when it is missing.
the name wantedABCDin all
at place 111103
at place 212216
at place 313329
at place 4144312
not in the list154414
Each instruction's runs on 4 names. Each place further on adds a B, a C and a D. With no name, one more D and one more B make 12 + 2 = 14.

The best case is the input of that size that costs least: 3. The worst case costs most: 14. The average case is no single input. It is the mean cost over a set of inputs, so it names the set. Over the 4 places, 3, 6, 9 and 12 make 30, and 30 over 4 is 7.5. Count the list without the name as a fifth input, and 30 + 14 = 44, and 44 over 5 is 8.8.

A bound, OO, Ω\Omega or Θ\Theta, says how a case's cost grows with the size. For nn names, the best case stays 3, so it is in O(1)O(1). The worst, 3n+23n + 2, 14 at 4 names, is in Θ(n)\Theta(n). The average over the nn places is 3(n+1)2\frac{3(n + 1)}{2}, 7.5 at 4 names, a little over half of 14. It is in Θ(n)\Theta(n) too. Questions 1 to 4 prove each.

instructions runnames0102030400246810instructions runnames0102030400246810
  • the worst case, 3n+23n + 2
  • the average, 3(n+1)2\frac{3(n + 1)}{2}
  • the best case, 3
The three cases for 1 to 10 names. The best stays at 3, the worst climbs 3 a name, and the average half as fast.

The worst case is a guarantee: no input of that size costs more, whoever supplies it. The best case is seldom much use, since you rarely choose your input.

Sorts put numbers in order, each its own way, as the table shows, and differ in three more ways. First, a sort works in place when it needs no second list to work in. Second, a sort keeps equal numbers in order, and is called stable, when equal numbers end in the order they started. Selection sort does not. Sort Ann 20, Bo 20 and Cy 19, in name order, by age, as drawn: selection sort gives Cy, Bo, Ann, and the name order is lost.

sorthow it worksin placekeeps equal numbers in order
bubbleswaps neighbours out of order, each walk one shorter; stops after a walk with no swapyesyes
insertionwalks each number left past bigger onesyesyes
selectionswaps the smallest left into each place in turn, unless it is there alreadyyesno
mergemerges sorted stretches in pairs into a second listnoyes
Four sorts and two ways they differ.
2a2b1the row12b2aafter pass 112b2aafter pass 2
Selection sort on 2, 2, 1, the 2s told apart as 2a and 2b, heavy lines for them, dashed for the 1. Pass 1 swaps the 1 to the front, carrying 2a past 2b.

Third, a sort may compare just as often whatever the order of its row. Selection sort makes 10 on every order of 5 numbers, so its best, worst and average are all 10 (question 5). Bubble and insertion sort make from 4, on a row in order, to 10, back to front (5, 4, 3, 2, 1). Insertion sort's 4 later numbers make at least 1 comparison each and at most one per number before: 4 to 1 + 2 + 3 + 4 = 10. One row can be dear for one and cheap for the other. On 2, 3, 4, 5, 1, bubble sort makes 10 and insertion sort 7, as question 5 draws.

23451start23415walk 14 pairs compared23145walk 23 pairs compared21345walk 32 pairs compared12345walk 41 pair comparedone walkin place for good
Bubble sort on 2, 3, 4, 5, 1. Each walk moves the 1 just one place left, so 4 + 3 + 2 + 1 = 10 comparisons.
12345start12345walk 14 pairs, no swapone walkin place for good
Bubble sort on 1, 2, 3, 4, 5. Walk 1 swaps nothing, so it stops after 4 comparisons.

where the formulas come from

Each question is worked out one numbered line at a time. A line shows the move it makes, the line itself, and why the move is allowed. A line either follows from the lines above it, or brings in something the question needs, such as how the method works, a small fact about nn, or a result from another page, with its own reason. Press 'hide the lines, then guess each one' to cover the lines and uncover them one by one, guessing each before you see it.

question 1What does the cheapest list cost? Call it UU.
  1. the move: find the cheapest list

    the line:
    the cheapest list has thename wanted at place 1\begin{gathered} \text{the cheapest list has the} \\ \text{name wanted at place 1} \end{gathered}

    why it is allowed: Every list has at least one name, so every list runs A, then B and C at place 1: at least 3. With the name wanted at place 1, C stops the method there.

  2. the move: count the cheapest list

    the line:
    U=1+1+1U = 1 + 1 + 1

    why it is allowed: By line 1, A, B and C run once each.

  3. the move: add them

    the line:
    U=3U = 3

    why it is allowed: Three 1s make 3, at any length.

  4. the move: read it as a ceiling

    the line:
    U≤3U \le 3

    why it is allowed: By line 3, UU is 3 at every length, so at most 3.

  5. the move: read it as a bound

    the line:
    U∈O(1)U \in O(1)

    why it is allowed: Big O of 1 needs a ceiling of a fixed number above zero times 1; by line 4, 3 serves.

try it with a small nn: at n=4n = 4, line 2 gives U=3U = 3, which you can work out by hand

question 2What does the dearest list cost? Call it VV.
  1. the move: find the list that costs most

    the line:
    the list that costs most doesnot hold the name wanted\begin{gathered} \text{the list that costs most does} \\ \text{not hold the name wanted} \end{gathered}

    why it is allowed: The method visits each place at most once and stops by place n+1n + 1, past the end. So A runs at most once, B at most n+1n + 1 times, C and D at most nn times. Without the name, C never stops it, so each runs its most, as the table of runs shows.

  2. the move: count that list

    the line:
    V=1+(n+1)+n+nV = 1 + (n + 1) + n + n

    why it is allowed: By line 1.

  3. the move: use the count of counting basic steps

    the line:
    V=3n+2V = 3n + 2
    where does this come from?
    question 1 of the page counting basic stepsHow many instructions run when the name is not in a list of nn names?
    1. the move: follow the walk

      the line:
      the method visitsplaces 1 to n+1\begin{gathered} \text{the method visits} \\ \text{places 1 to } n + 1 \end{gathered}

      why it is allowed: A starts at place 1. At each place with a name, B lets the method through, C looks and does not stop it, and D moves it on. At place n+1n + 1, B finds no name and stops it.

    2. the move: count instruction A\mathrm{A}

      the line:
      A runs once\text{A runs once}

      why it is allowed: A runs at the start, and nothing goes back to it.

    3. the move: count instruction B\mathrm{B}

      the line:
      B runs n+1 times\text{B runs } n + 1 \text{ times}
      where the method isBCD
      place 1runsrunsruns
      place 2runsrunsruns
      place 3runsrunsruns
      place 4runsrunsruns
      place 5runs, and stops
      in all544
      A list of 4 names without the name wanted: B runs 5 times, C and D 4 times each.

      why it is allowed: B runs at every place visited, places 1 to n+1n + 1 by line 1.

    4. the move: count instruction C\mathrm{C}

      the line:
      C runs n times\text{C runs } n \text{ times}

      why it is allowed: C runs at each place with a name, places 1 to nn by line 1.

    5. the move: count instruction D\mathrm{D}

      the line:
      D runs n times\text{D runs } n \text{ times}

      why it is allowed: D runs after each run of C, since by line 1 C never stops the method.

    6. the move: add them up

      the line:
      T=1+(n+1)+n+nT = 1 + (n + 1) + n + n

      why it is allowed: Let TT count every run of every instruction. Add lines 2 to 5.

    7. the move: add like with like

      the line:
      T=3n+2T = 3n + 2

      why it is allowed: The three lots of nn make 3n3n, and the two 1s make 2. For 4 names, 14.

    8. the move: a fact for the ceiling

      the line:
      2≤2n2 \le 2n

      why it is allowed: Another way of counting gives another exact formula. So trap TT between two multiples of nn. First a fact: nn is at least 1, so 2 is at most 2n2n.

    9. the move: a ceiling

      the line:
      T≤3n+2nT \le 3n + 2n

      why it is allowed: By line 8, swap the 2 in line 7 for 2n2n, which is no smaller.

    10. the move: add like with like

      the line:
      T≤5nT \le 5n

      why it is allowed: 3n3n and 2n2n make 5n5n.

    11. the move: think of TT at every length at once

      the line:
      T for everylength of list at once\begin{gathered} T \text{ for every} \\ \text{length of list at once} \end{gathered}
      namesinstructions run5 times the names
      155
      2810
      41420
      103250
      100302500
      At every length, the count stays at or under 5 times the names.

      why it is allowed: Lines 1 to 10 hold for every list of at least one name. So read TT as the whole graph of counts against lengths, not one point.

    12. the move: read it as a bound

      the line:
      T∈O(n)T \in O(n)
      namestwice the names and 20 more3 times the names
      1223
      104030
      206060
      308090
      100220300
      A made-up count breaks the ceiling of 3 times the names below 20 names and meets it at 20. Each name more adds 2 to the count and 3 to the ceiling.

      why it is allowed: O(n)O(n) is the group of counts that, from some length on, never climb above a fixed number above zero times nn. Short lists may break it, as in the table beside this line. By line 10, 5 serves for TT. Read TT is in big O of nn.

    13. the move: a floor

      the line:
      T≥3nT \ge 3n
      102104106108101102103104105106107101102103104105106107108101102103104105106107
      • the count of instructions run, 3n+23n + 2
      • the ceiling of line 10, 5n5n
      • the floor of this line, 3n3n
      A log-log plot: each step across or up is ten times the one before. Multiplying by the same number moves up the same distance. So a line always the same multiple of another stays the same distance above it: 50 sits as far above 30 as 500 above 300. The count, the heavy line, stays between 5n5n and 3n3n.

      why it is allowed: Leave the 2 out of line 7. What is left is smaller.

    14. the move: read it as a bound

      the line:
      T∈Ω(n)T \in \Omega(n)

      why it is allowed: Ω(n)\Omega(n) is the same with a floor: from some length on, never below a fixed number above zero times nn. By line 13, 3 serves for TT. Read TT is in big omega of nn.

    15. the move: a ceiling and a floor together

      the line:
      T∈Θ(n)T \in \Theta(n)

      why it is allowed: By lines 10 and 13, TT stays between 3n3n and 5n5n; lines 12 and 14 read both as bounds with the same term, nn. That is the tight bound, read TT is in theta of nn: TT grows like nn. Counting the basic steps gives 3 and 20 instead (question 4 of the page counting basic steps); the term stays nn.

    the whole page: counting basic steps

    why it is allowed: The box above opens question 1 of counting basic steps; its TT is this VV. Its line 7 adds the same runs, and its lines 8 to 15 put 3n+23n + 2 in Θ(n)\Theta(n). For 4 names, 14.

try it with a small nn: at n=4n = 4, line 2 gives V=14V = 14, which you can work out by hand

question 3What does a list cost on average, with the name equally likely at each place? Call it MM.
  1. the move: count the list with the name at place k

    the line:
    at place k, the cost is1+k+k+(k−1)\begin{gathered} \text{at place } k \text{, the cost is} \\ 1 + k + k + (k - 1) \end{gathered}

    why it is allowed: A runs once, B and C at places 1 to kk, and D at each place before kk, as the table of runs at the top shows.

  2. the move: average the cost over the places

    the line:
    M=1n∑k=1n(1+k+k+(k−1))M = \frac{1}{n} \sum_{k=1}^{n} (1 + k + k + (k - 1))

    why it is allowed: Add line 1 over the nn places, then share the total among them. Read ∑\sum as add up, for kk from 1 to nn. For 4 names, 30 over 4 is 7.5.

  3. the move: add like with like

    the line:
    M=1n∑k=1n3kM = \frac{1}{n} \sum_{k=1}^{n} 3k

    why it is allowed: The 1 and the 1 taken away cancel, and three lots of kk make 3k3k.

  4. the move: take out the 3

    the line:
    M=1n×3∑k=1nkM = \frac{1}{n} \times 3 \sum_{k=1}^{n} k

    why it is allowed: Each part has a 3. For 4 names, 3, 6, 9 and 12 add to 3 times the sum of 1, 2, 3 and 4.

  5. the move: put the 3 over n

    the line:
    M=3n∑k=1nkM = \frac{3}{n} \sum_{k=1}^{n} k

    why it is allowed: 1n\frac{1}{n} times 3 is 3n\frac{3}{n}.

  6. the move: a fact about adding up

    the line:
    ∑k=1nk=n(n+1)2\sum_{k=1}^{n} k = \frac{n(n + 1)}{2}
    Two staircases of 1 to 4 squares fill 4 columns of 5, 20 squares. One staircase is half, 10.

    why it is allowed: Write 1 to nn in a row, and again backwards under it. Each of the nn columns adds to n+1n + 1, so the two rows hold n(n+1)n(n + 1), twice the sum. Halve it.

  7. the move: use line 6

    the line:
    M=3n×n(n+1)2M = \frac{3}{n} \times \frac{n(n + 1)}{2}

    why it is allowed: By line 6, the sum in line 5 is n(n+1)2\frac{n(n + 1)}{2}.

  8. the move: write it as one fraction

    the line:
    M=3n(n+1)2nM = \frac{3n(n + 1)}{2n}

    why it is allowed: Two fractions multiplied make one, tops multiplied over bottoms multiplied.

  9. the move: cancel the n

    the line:
    M=3(n+1)2M = \frac{3(n + 1)}{2}

    why it is allowed: The nn on top and below divide out, as nn is above zero. For 4 names, 7.5.

  10. the move: multiply out the bracket

    the line:
    M=3n+32M = \frac{3n + 3}{2}

    why it is allowed: 3 times (n+1)(n + 1) is 3n3n and 3.

  11. the move: write 3 as 2 and 1

    the line:
    M=(3n+2)+12M = \frac{(3n + 2) + 1}{2}

    why it is allowed: 3 is 2 and 1, written so that the worst case's 3n+23n + 2 shows.

  12. the move: halve each part

    the line:
    M=3n+22+12M = \frac{3n + 2}{2} + \frac{1}{2}
    namesbestaverageworsthalf the worst, plus 0.5
    437.5147.5
    1,00031,501.53,0021,501.5
    By questions 1 and 2 and line 9; the last column is line 13.

    why it is allowed: Half a total is half of each part.

  13. the move: set it beside the worst case

    the line:
    half the worst case,plus one half\begin{gathered} \text{half the worst case,} \\ \text{plus one half} \end{gathered}

    why it is allowed: By line 12, the average is half of question 2's worst case, plus one half. For a long list the half hardly counts.

try it with a small nn: at n=4n = 4, line 2 gives M=7.5M = 7.5, which you can work out by hand

question 4How does the average grow? Call it MM again.
  1. the move: start from the average

    the line:
    M=3(n+1)2M = \frac{3(n + 1)}{2}

    why it is allowed: Line 9 of question 3.

  2. the move: a fact for the ceiling

    the line:
    n+1≤2nn + 1 \le 2n

    why it is allowed: Big O of nn needs a ceiling of a fixed number times nn. As 1 is at most nn, add nn to both, and n+1n + 1 is at most 2n2n. At 4, 5 is under 8.

  3. the move: a ceiling

    the line:
    M≤3×2n2M \le \frac{3 \times 2n}{2}

    why it is allowed: By line 2, swap the n+1n + 1 in line 1 for 2n2n, which is no smaller.

  4. the move: multiply the top

    the line:
    M≤6n2M \le \frac{6n}{2}

    why it is allowed: 3 times 2n2n is 6n6n.

  5. the move: halve it

    the line:
    M≤3nM \le 3n

    why it is allowed: Half of 6n6n is 3n3n.

  6. the move: read it as a bound

    the line:
    M∈O(n)M \in O(n)

    why it is allowed: By line 5, MM is at most 3 times nn from 1 name on, and 3 is above zero.

  7. the move: a floor

    the line:
    M≥3n2M \ge \frac{3n}{2}

    why it is allowed: Leave the 1 out of n+1n + 1 in line 1. What is left is smaller.

  8. the move: read it as a bound

    the line:
    M∈Ω(n)M \in \Omega(n)
    instructions runnames01020300246810instructions runnames01020300246810
    • the average, 3(n+1)2\frac{3(n + 1)}{2}
    • the ceiling of line 5, 3n3n
    • the floor of line 7, 3n2\frac{3n}{2}
    The average between its ceiling and floor, 1 to 10 names. At 4 names, 7.5, 12 and 6.

    why it is allowed: By line 7, MM is at least one and a half times nn from 1 name on, a fixed number above zero.

  9. the move: a ceiling and a floor together

    the line:
    M∈Θ(n)M \in \Theta(n)

    why it is allowed: Lines 6 and 8 give a ceiling and a floor with the same term, nn, the part in brackets. So the average grows like nn, as the worst case does.

try it with a small nn: at n=4n = 4, line 1 gives M=7.5M = 7.5, which you can work out by hand

question 5How many comparisons does selection sort make on a row of nn numbers? Call it SS.
  1. the move: count the comparisons at place k

    the line:
    filling place k takesn−k comparisons\begin{gathered} \text{filling place } k \text{ takes} \\ n - k \text{ comparisons} \end{gathered}
    23451the row13452after pass 112453after pass 212354after pass 312345after pass 4
    Selection sort on 2, 3, 4, 5, 1. Its passes make 4, 3, 2 and 1 comparisons, each with one swap, 10 comparisons and 4 swaps in all.
    place filledcompared withcomparisons
    1places 2 to 54
    2places 3 to 53
    3places 4 and 52
    4place 51
    in all10
    Selection sort on any row of 5 numbers.

    why it is allowed: Selection sort fills places 1 to n−1n - 1 in turn; the last number left is the biggest. For place kk, it compares the smallest so far with each number after place kk.

  2. the move: add them over the places

    the line:
    S=∑k=1n−1(n−k)S = \sum_{k=1}^{n - 1} (n - k)

    why it is allowed: Line 1 for places 1 to n−1n - 1, added, for a row of at least 2 numbers.

  3. the move: write the sum out

    the line:
    S=(n−1)+(n−2)+⋯+1S = (n - 1) + (n - 2) + \dots + 1

    why it is allowed: Place 1 takes n−1n - 1, each place after it one fewer, down to 1. For 5 numbers, 4 + 3 + 2 + 1; for 2 numbers, just 1.

  4. the move: add them the other way round

    the line:
    S=1+2+⋯+(n−1)S = 1 + 2 + \dots + (n - 1)

    why it is allowed: The same numbers in the other order make the same total, 1 + 2 + 3 + 4 for 5.

  5. the move: use the adding up of question 3

    the line:
    S=(n−1)((n−1)+1)2S = \frac{(n - 1)((n - 1) + 1)}{2}

    why it is allowed: Line 6 of question 3 adds up 1 to nn, for any nn from 1. Here the last number is n−1n - 1, at least 1, so put it for nn.

  6. the move: add the 1

    the line:
    S=(n−1)n2S = \frac{(n - 1)n}{2}

    why it is allowed: n−1n - 1 and 1 make nn. For 5 numbers, 10.

  7. the move: read it

    the line:
    the same for everyorder of the row\begin{gathered} \text{the same for every} \\ \text{order of the row} \end{gathered}
    23451start23451walk 11 pair, no swap23451walk 21 pair, no swap23451walk 31 pair, no swap12345walk 44 pairs comparedone walkin place for good
    Insertion sort on 2, 3, 4, 5, 1. The 3, 4 and 5 each stop after one comparison; the 1 walks to the front. 1 + 1 + 1 + 4 = 7.
    a row of 5bubble sortinsertion sortselection sort
    in order4410
    2, 3, 4, 5, 110710
    back to front101010
    every order, on averageabout 9.26about 7.7210
    Comparisons on rows of 5, averaged over all 120 orders. Any of 5 can go first, any of the 4 left second, and so on, 5 × 4 × 3 × 2 × 1. Only selection sort's never change.

    why it is allowed: Line 1 depends on the row's length, never its order, so every order of 5 costs 10. Insertion sort's cost changes with the order, as drawn.

  8. the move: read it as cases

    the line:
    for comparisons, its best, worstand average cases are one\begin{gathered} \text{for comparisons, its best, worst} \\ \text{and average cases are one} \end{gathered}

    why it is allowed: By lines 6 and 7, every row of nn numbers costs the same, 10 for 5. So its best, worst and average are one number.

try it with a small nn: at n=4n = 4, line 2 gives S=6S = 6, which you can work out by hand

a worked example

The three cases on a list of 5 names.

  1. Best, the name wanted at place 1: A, B and C, 3 instructions.
  2. With the name at places 1 to 5: 3, 6, 9, 12 and 15, 3 for each place reached.
  3. Average over the 5 places: they make 45, and 45 over 5 is 9. 3(n+1)2\frac{3(n + 1)}{2} gives 9 for 5.
  4. Worst, the name missing: 17 instructions. 3n+23n + 2 gives 17 for 5.

the trap

check yourself

  1. For 'look at every name' on a list of 10 names, what do the best case, the worst case and the average over the 10 places cost?

    the answer

    3 at best and 32 at worst. Over the 10 places, 3, 6, 9 and on up to 30 make 165, and 165 over 10 is 16.5.

  2. Selection sort makes 10 comparisons on every row of 5. Is every row then its best and worst case, for comparisons and for swaps?

    the answer

    For comparisons, yes. For swaps, no. A row in order needs none, and 2, 3, 4, 5, 1 needs 4, one at each place filled. A case is for one count.

  3. Sort Ann 20, Bo 20 and Cy 19 by age with insertion sort instead. In what order do they end?

    the answer

    Cy, Ann, Bo. Insertion sort keeps equal numbers in order, so Ann stays before Bo.