TactivergeLite

Lite / Intelligent Robotic Systems / Week 5

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 · Full interactive version

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.

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?

  1. About 2
  2. About 20
  3. About 200
  4. Never
Guess first, then reveal

About 20. Without sorting, k searches cost about 512k; with sorting, about 10,240 + 11k. These cross when 501k ≈ 10,240, so k ≈ 20. Beyond that, sorting wins by more every time.

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?

What the interactive shows (text version)

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.

You can also open the interactive on the full site when you have a faster connection.

Watch (optional)

Watch for: 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.

“Intro to Algorithms: Crash Course Computer Science #13” by CrashCourse (opens YouTube; streaming video uses a lot of data)

The video is optional. Everything you need is in this lesson's text.

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

Intuitive

Tidying your toolbox takes ten minutes. If you need one spanner today, just rummage. If you'll need tools all term, tidy once.

Technical

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.

Mathematical

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.

Applied

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 first

Common mix-ups

Practice

Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.

comparisons

Practice 2. You must repeatedly list every part number between 2000 and 2100. Which preparation is best?

comparisons

Practice 4. You need to check ONE part number in an unsorted list of 50,000, once. Best plan?

searches

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.

Reflect

What was the most surprising difference between the comparison-count prediction and your measured times?

Write your answer on paper or in your own notes. Lite never stores what you write.

Go further

← Insertion sort: tidy as you goCount the steps before you time them →