Skip to content
Exit presentation

Programming Proper II: Functions, Lists & Simple Algorithms

Counting both searches

Two searches, one board. Which one does less work? The worst case is when a search needs the most checks.

8 fares: walk 8, halving 4.
Step 1 of 4
  1. 8 fares: walk 8, halving 4.
  2. 16 fares: walk 16, halving 5.
  3. 32 fares: walk 32, halving 6.
  4. 64 fares: walk 64, halving 7.

The rule

Halving does less work. The gap grows as the list grows.

Count comparisons, not seconds. In the worst case, doubling the list doubles the walk. It adds one comparison to halving.

A comparison is one check of an item against the wanted fare. We count these because a clock changes from phone to phone.

The walk is worst when the fare is last, or missing. It then checks every fare. Halving is worst for a missing fare. It halves the list until nothing is left.

Worst-case comparisons
Fares on the boardThe walkHalving
884
16165
32326
64647

The walk's count grows as fast as the list. Halving's count grows slowly.

Guess the halving count. Then read both bars.

Loading lab…

Jump to lesson

This track

  1. 0 Start here
  2. 1 Is it there at all?
  3. 2 The counted loop
  4. 3 In order first
  5. 4 Counting both searches
  6. 5 One pass, and the box in the middle
  7. 6 The whole sort, written down
  8. 7 Sort once, search many
  9. 8 How the count grows
  10. 9 The big picture
  11. 10 Track quiz

Other tracks