Sort once, search many: when sorting pays
Sorting 10,000 part numbers costs work up front. After how many lookups has it paid for itself?
About 35 min · 3 goals · Checked by automated tests
1.Why should I care?
Engineering is about total cost, not the cost of one step. Sorting is an investment: you pay once and every later search is cheap. Knowing when that investment pays off, and when a set beats both, is the kind of judgement that separates working code from good code.
- ◇ Estimate the total cost of k searches with and without sorting first.
- ◇ Find the break-even number of searches for a given data size.
- ◇ Choose between linear search, sort-then-binary-search and a set for a realistic task.
2.Predict
A list has 1,024 unsorted items. Sorting costs about n·log₂ n ≈ 10,000 comparisons; each later binary search costs about 11. A linear search costs about 512 on average. Roughly how many searches before sorting first is cheaper?
Guess first. Being wrong here is how the surprise works.
3.Understand
Total cost is what matters
With n items and k searches, linear search costs about k·n/2 comparisons. Sorting costs about n·log₂ n with a good sort, then each binary search about log₂ n. Write both totals and compare them for your actual n and k.
The break-even point
Set k·n/2 = n·log₂ n + k·log₂ n and solve for k. For large n the break-even is roughly k ≈ 2·log₂ n: only a few dozen searches even for millions of items. If you'll search more than that, sort first.
Or skip ordering entirely
If you only ask 'is it there?' or 'what's its value?', building a set or dict costs about n steps and each lookup about 1. Sorting still wins when you need order: ranges ('all parts between 2000 and 2100'), nearest values, or the top ten.
Explain it another way
Tidying your toolbox takes ten minutes. If you need one spanner today, just rummage. If you'll need tools all term, tidy once.
Costs, in comparisons: linear k·n/2 average; sort + binary n log₂ n + k log₂ n; set build ≈ n hashes, then ≈ 1 per lookup. Real timings also depend on constants: Python's sorted() runs in optimised C, so measured break-evens can differ from the comparison count.
Break-even: k·n/2 = (n + k)·log₂ n gives k = n·log₂ n / (n/2 − log₂ n). For n = 1024: k = 10240 / (512 − 10) ≈ 20.4.
Databases make exactly this trade-off when they build an index: extra cost on every insert, in exchange for fast lookups and range queries on every read.
Worked example 1
Compare comparison counts for k lookups on n = 1024 items.
import math
n = 1024
log_n = math.log2(n)
for k in [1, 10, 20, 21, 100]:
linear = k * n / 2
sort_then_binary = n * log_n + k * log_n
better = "sort first" if sort_then_binary < linear else "linear"
print(k, int(linear), int(sort_then_binary), better)
# 1 512 10250 linear
# 10 5120 10340 linear
# 20 10240 10440 linear
# 21 10752 10450 sort first
# 100 51200 11240 sort firstCommon mix-ups
- Sorting is always worth it before searching.
✓ Only if you'll search enough times, or need order (ranges, nearest values). - Comparison counts predict exact timings.
✓ They predict growth. Constant factors (C versus Python loops, memory) shift the real break-even.
4.Discover
In the Code Lab, generate 5,000 random part numbers and 1,000 lookups. Time three strategies: linear search each time, sorted() then bisect, and a set. Repeat with only 5 lookups. Which strategy wins in each case, and by roughly how much?
Can't use the interactive? Read a description instead
The Code Lab activity can be done on paper with the cost models: for n = 1024, linear search costs 512 comparisons per lookup; sorting costs about 10,240 once plus 10 per lookup. Linear is cheaper up to 20 lookups; sorting first is cheaper from 21 lookups.
5.Checkpoint: guided practice
Check what you just discovered before going on. Hints appear after a wrong answer.
Practice 1
Linear search averages n/2 comparisons. For n = 2,000 items and k = 30 lookups, about how many comparisons in total?
6.Watch
→ Watch for how the cost of sorting is described and compared, and why the order of growth matters.
Shows how a step-by-step recipe of decisions and repeats lets a machine solve a problem such as sorting.
Length: see YouTube · captions on YouTube · source
Nothing loads from YouTube until you press play.
The video is optional: everything you need is also in the lesson text and the interactive.
7.Practice on your own
Practice, not a test. Wrong answers get a hint and another try.
Practice 2
You must repeatedly list every part number between 2000 and 2100. Which preparation is best?
Practice 3 · a fresh version every time
A sorted list holds 50 calibration points. Binary search compares the target with one middle element per loop and halves the range each time. In the worst case (including a target that is not there), how many elements does it compare with the target?
Practice 4
You need to check ONE part number in an unsorted list of 50,000, once. Best plan?
Practice 5
Using cost models linear = k·n/2 and sorted = n·log₂n + k·log₂n, with n = 256, what is the smallest whole number of searches k for which sorting first is cheaper?
8.Apply it
Write up the Code Lab experiment as a short investigation: question, three strategies, n and k values, a table of measured times (best of five runs), and a conclusion about which strategy you'd use for a stores catalogue that is searched 200 times a day and updated once a week.
9.Reflect
10.Go further
- Python docs: timeit ↗How to time small pieces of code fairly, with repeats.
Concepts: Algorithms, searching and complexity