Exercise 24 of 30 · intermediate · sorting · binary search · linearithmic

Sort once, then binary search n times

The code

items.sort()                      # n log n comparisons
for q in queries:                 # n queries
    found = binary_search(items, q)

What is the total compared with n linear searches?

Count: comparisons.

Measured counts

020k40k60k20004000ncount
Measured
Table
ncount
844
16112
32272
64640
1281,472
2563,328
5127,424
102416,384
204835,840
409677,824

Try to name the class from the shape before opening the answer.

Show the answer and derivation
Time
Θ(n log n)
Extra space
depends on the sort (O(n) for merge sort)
  1. Sorting: Θ(n log n) comparisons.
  2. n binary searches: n × O(log n) = Θ(n log n).
  3. Sum: Θ(n log n), versus n × Θ(n) = Θ(n²) for n linear searches. A hash set would give Θ(n) expected.

Common mistake: Forgetting the cost of sorting, or re-sorting inside the loop (n · n log n).

Check: measured count ÷ (n log n) settles near 1.58 for large n.