Python 3D Academyবাংলা

Halving the search: lo, hi and the guessing game

🌍 In real life. "I'm thinking of a number from 1 to 100. Guess it, and I'll say higher or lower." Guessing 1, 2, 3, … could take 100 guesses. The clever player says 50 first: whatever the answer, half the numbers are gone. Then 25 or 75, then the middle of what is left. Seven guesses always find it, because 100 halves to 1 in seven steps.

The same trick finds a word in a dictionary, a name in a sorted register, or a value in a sorted list. It only needs one thing: the items are in order, so one look at the middle tells you which half to throw away.

The idea in one sentence: keep two markers, lo and hi, around the part of a sorted list where the target can still be; look at the middle, and move lo past it or hi before it, until you find the target or the part is empty.

Its words:

  • binary search: searching by halving the part that is left, one look at a time
  • lo and hi: the first and last positions still in play
  • mid: the middle position, (lo + hi) // 2
  • invariant: a fact that is true before every look; here, if the target is in the list, it is somewhere in a[lo] … a[hi]

Step by step:

  1. lo, hi = 0, len(a) - 1: the whole list is in play
  2. while lo <= hi: mid = (lo + hi) // 2
  3. a[mid] == target? Found: return mid
  4. a[mid] < target? Everything up to mid is too small: lo = mid + 1
  5. otherwise everything from mid on is too big: hi = mid - 1
  6. the loop ends with lo > hi: nothing is left, so the target is not there: return -1

And when the target is not there, lo and hi cross:

Why it is correct. The invariant holds at the start (the whole list is in play) and every look keeps it true. If a[mid] < target, then because the list is sorted, a[lo] to a[mid] are all smaller than the target too, so none of them is it: moving lo to mid + 1 throws away only wrong answers. The same goes for hi on the other side. So when the part is empty, the target was never in the list. And the part shrinks at every look, so the loop must end.

What it costs, by counting. Each look halves what is left, so the looks needed are about log₂ n + 1:

  • 10 items: at most 4 looks
  • 1000 items: at most 10
  • 1,000,000 items: at most 20
  • 1,000,000,000 items: at most 30

O(log n): doubling the list adds just one look, where checking one by one (O(n)) doubles the work. The price: the list must be sorted first (Chapter 45), so binary search pays off when you search the same list many times.

The code. Python's bisect module (Chapter 30) does the same halving for you: bisect_left(a, x) is where x is or would go, so x is in the list when that position holds x:

import bisect

def search(a, target):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == target:
            return mid
        if a[mid] < target:
            lo = mid + 1             # the target can only be to the right
        else:
            hi = mid - 1             # the target can only be to the left
    return -1

a = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
print(search(a, 23), search(a, 30), search(a, 91), search([], 5))

i = bisect.bisect_left(a, 23)          # the library way
print(i, i < len(a) and a[i] == 23)

Mistakes and edge cases.

  • while lo < hi with hi = len(a) - 1: when one item is left, lo == hi, and the loop stops without looking at it; the last or only item is never found
  • lo = mid or hi = mid in this template: when lo and hi are next to each other, mid stays the same and the loop never ends; move past mid
  • an unsorted list: binary search gives wrong answers without any error; sort first, or search one by one
  • an empty list: hi starts at -1, so lo <= hi is False at once and the answer is -1, with no special case

Quiz

  1. What does this print?

    a = [3, 6, 9, 12, 15, 18, 21, 24]
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        print(mid, end=" ")
        if a[mid] == 21:
            break
        if a[mid] < 21:
            lo = mid + 1
        else:
            hi = mid - 1
  2. At most how many looks does binary search need on a sorted list of 1000 items?

    • 10
    • 500
    • 100
    • 1000
  3. search([4, 7], 7) gives -1, but 7 is at position 1. Which line is wrong?

    def search(a, target):
        lo, hi = 0, len(a) - 1
        while lo < hi:
            mid = (lo + hi) // 2
            if a[mid] == target:
                return mid
            if a[mid] < target:
                lo = mid + 1
            else:
                hi = mid - 1
        return -1
  4. Which fact stays true before every look, and is the reason binary search is correct?

    • If the target is in the list, it is somewhere in a[lo] … a[hi]
    • a[mid] is always the target
    • lo and hi always move by one
  5. What happens if you binary search a list that is not sorted?

    • It can quietly give a wrong answer: one look no longer tells which half to drop
    • Python raises an error
    • It is just slower

Coding tasks

  1. Write binary_search(nums, target) for a sorted list: the position of target, or -1 if it is not there. Each look must halve the part left: on 1000 items it may compare at most 40 times.

  2. Play the guessing game. Write guess_number(low, high, check): the secret is a whole number from low to high; check(g) returns 0 if g is the secret, -1 if the secret is lower than g, and 1 if it is higher. Return the secret, using at most 10 guesses for 1 to 1000.