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.

After only two checks a quarter of the data remains.
The wayHow many checksWhat is required
Going overAs many as the list’s sizeNothing
HalvingVery fewA 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 -1

What 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

  1. Look at the middle item.
  2. If the target is larger — it is in the right half.
  3. Give up the whole left half.
  4. And repeat on what remains.

Example 2 — why the difference grows

  1. The number of items is doubled.
  2. The going-over is doubled too.
  3. The halving gains only one check.
  4. So the gap grows as the data grows.
Each check erases half of what is left — provided the list is sorted.