Halving the Search
Order lets a search throw away half the collection at every step, which turns a million comparisons into twenty. The whole course is about keeping that possible while the data changes.
The last course gave up order to get an instant lookup. This one takes order
seriously, and the first thing order buys is that a single comparison can
eliminate half of everything.
| step | step | range still possible | middle item | comparison | what is left |
|---|---|---|---|---|---|
| 1 | 1 | 1 to 100 | 50 | 73 is larger | 51 to 100 |
| 2 | 2 | 51 to 100 | 75 | 73 is smaller | 51 to 74 |
| 3 | 3 | 51 to 74 | 62 | 73 is larger | 63 to 74 |
| 4 | 4 | 63 to 74 | 68 | 73 is larger | 69 to 74 |
| 5 | 5 | 69 to 74 | 71 | 73 is larger | 72 to 74 |
| 6 | 6 | 72 to 74 | 73 | found |
- the number of items in the collection
- the number of halvings until one item is left
import bisect, random, time
n = 1_000_000
items = sorted(random.sample(range(10 * n), n))
wanted = random.sample(items, 1000)
t = time.perf_counter()
for k in wanted:
bisect.bisect_left(items, k)
print('thousand searches, seconds', round(time.perf_counter() - t, 5))
t = time.perf_counter()
for k in random.sample(range(10 * n), 1000):
bisect.insort(items, k)
print('thousand insertions, seconds', round(time.perf_counter() - t, 5))
chain = {'value': 1, 'next': None} # a chain inserts without moving anything
chain['next'] = {'value': 2, 'next': None}
print('can this chain reach its middle directly:', False)The tension the course resolves
The halving search needs two things: order, and the ability to jump to the
middle. A block of memory gives both and makes insertion cost half the
collection.
A chain gives cheap insertion and no way to reach the middle. The next lesson
builds the structure that gives both at once, and the four after that are
about keeping it honest.
Recap
- A comparison against the middle of a sorted collection eliminates half of it, so the number of comparisons is the number of halvings rather than the number of items.
- That is twenty comparisons at a million and thirty at a thousand million, which means the method barely notices the collection growing.
- It requires order and the ability to jump straight to the middle, and the second requirement is the one that quietly fails when the collection has to change.
This is the reading half
Starting the course gives you your own copy of it. Every idea on every page has problems standing under it, marked with a reason rather than a tick, and any sentence you do not believe can be opened and argued with. None of that can happen on a page nobody owns.
The contents