Start free

Advanced · Searching · 197 of 264

Binary search

Find a number in a sorted list with binary search: look at the middle and keep whichever half can still contain it. Print its position (from 0), or -1.

Input: sorted whole numbers on one line (all different), then the number to find. Output: its position or -1

Examples

Input
1 3 5 7 9 11
7
Output
3
Input
1 3 5
4
Output
-1
Input
2
2
Output
0

2 more tests check other inputs when you press Check.

Stuck? The idea behind searching

Linear search looks at each item in turn. Binary search works on a sorted list: look at the middle, then throw away the half that can't hold the answer.

Binary search finds an item among a million in about 20 steps.

def find(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

Watch for: lo = mid instead of mid + 1 can loop for ever when two items are left.

All the searching exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More searching exercises