Sign in

Lookup

Look up a concept

Type what you want to understand. If MonksBit has the lesson, you get the idea first: one sentence, a picture, one pass, and the smallest code.

Try it before you search

Binary search, the way a lesson opens. Switch level, step through the idea, and copy the code. Any lesson you look up works the same way.

Plain words. One step at a time. Nothing here assumes you already know the idea.

The idea

Binary search finds an item in a sorted list by checking the middle element and discarding the half that cannot contain it.

Watch it work

Look for
  1. 3 lo
  2. 8
  3. 12
  4. 17
  5. 23
  6. 31
  7. 42
  8. 50
  9. 64 hi

Press Step. The search starts with the whole row.

0 checks for 9 values
See it

Guessing a number between 1 and 100: each higher or lower answer is the comparison with the middle.

1 of 3

You will need. Arrays and indexes · Loops

One pass

Step 1 of 2

Start in the middle of a sorted row. If that value is too small, everything to its left is too small too.

Smallest version

Iterative binary search

def search(a, x):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == x:
            return mid
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

Keep these

  • The input must be sorted.
  • Each step halves the search space.

Try one

Find the first occurrence

easy

Look up the real lesson