Grade 8 Computer Science · Searching and sorting
Halving instead of going over
Two ways to find a value, and the difference between them on large data.
Twenty checks instead of a million
To find one name in a list of a million names you can check them one by one. There is a way that finds it in about twenty checks. It sounds like magic, it has a price, and whoever forgets the price will get “not found” for a name that is in the list.
Finding an item in a list is the simplest problem there is, and it is also the problem from which most is learned. The obvious way is to go over everything. There is a second way, and it is far better — but it demands something in return.
| The way | How many checks | What is required |
|---|---|---|
| Going over | As many as the list’s size | Nothing |
| Halving | Very few | A sorted list |
def binary_search(sorted_items, target):
low, high = 0, len(sorted_items) - 1
while low <= high:
mid = (low + high) // 2
if sorted_items[mid] == target:
return mid
if sorted_items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1What this is really worth
The numbers here are hard to grasp until they are seen. In a list of a thousand items, going over everything demands up to a thousand checks; halving the list demands ten. In a million items: a million checks against twenty. The difference is not “faster” but an entirely different kind of growth — each doubling of the data adds one check to the halving search, while it doubles the going-over. This is the idea that makes searching enormous quantities of data possible at all, and it lies at the base of nearly every system that looks something up.
Example 1 — following a halving
- Look at the middle item.
- If the target is larger — it is in the right half.
- Give up the whole left half.
- And repeat on what remains.
Example 2 — why the difference grows
- The number of items is doubled.
- The going-over is doubled too.
- The halving gains only one check.
- So the gap grows as the data grows.