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
- 3 lo
- 8
- 12
- 17
- 23
- 31
- 42
- 50
- 64 hi
Press Step. The search starts with the whole row.
Guessing a number between 1 and 100: each higher or lower answer is the comparison with the middle.
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 -1Keep these
- The input must be sorted.
- Each step halves the search space.
Try one
Find the first occurrence
easy