Skip to content
Exit presentation

Programming Proper II: Functions, Lists & Simple Algorithms

Sort once, search many

A conductor, who sells bus tickets, gets many fare questions. Should the board be sorted first?

3 questions: walk 21, sort then halve 30.
Step 1 of 4
  1. 3 questions: walk 21, sort then halve 30.
  2. 5 questions: walk 35, sort then halve 36.
  3. 6 questions: walk 42, sort then halve 39.
  4. 12 questions: walk 84, sort then halve 57.

The rule

It depends on the number of questions. On this board, sorting first needs fewer comparisons from 6 questions.

Walking needs no order. Halving needs the list sorted first. Sorting costs comparisons, paid once. Count the questions before you pay for order.

Take a board of 7 fares. A walk needs at most 7 comparisons per question. Halving needs at most 3.

Sorting 7 fares costs 21 comparisons in the worst case, paid once. That is 7 × 6 ÷ 2.

Count the worst case. Each question then saves 4 comparisons, 7 minus 3. After 5 questions, 20 are saved, less than the 21. After 6 questions, 24 are saved, more than the 21.

Worst-case comparisons for q questions
PlanComparisons
Walk every time7 × q
Sort once, then halve21 + 3 × q

At 5 questions, walking costs 35 and sorting first costs 36. At 6 questions, walking costs 42 and sorting first costs 39.

There is a third plan: halve without sorting. It is cheap, but it can be wrong. The six sample questions are 18, 9, 36, 15, 24 and 21. On the unsorted board, halving answers 2 of them wrongly.

Slide to the fewest questions where sorting wins.

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