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
Table
| n | count |
|---|---|
| 8 | 44 |
| 16 | 112 |
| 32 | 272 |
| 64 | 640 |
| 128 | 1,472 |
| 256 | 3,328 |
| 512 | 7,424 |
| 1024 | 16,384 |
| 2048 | 35,840 |
| 4096 | 77,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)
- Sorting: Θ(n log n) comparisons.
- n binary searches: n × O(log n) = Θ(n log n).
- 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.