SEARCHING · 10 MIN
Binary Search
On sorted data, compare with the middle and discard half each step — O(log n).
BYTE explains
- Keep two pointers lo and hi.
- mid = (lo + hi) // 2. If arr[mid] equals the target, done.
- If the target is bigger, move lo = mid + 1; otherwise hi = mid - 1.
- Stops when lo > hi — the target is absent.
Real world: Guessing a number from 1–100 with 'higher/lower' hints takes at most 7 guesses.
Watch it move
20
51
82
123
164
235
386
567
728
919
lo=0 hi=9 mid=4 → a[mid]=16
1/4
Code
def binary_search(a, t):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == t: return mid
if a[mid] < t: lo = mid + 1
else: hi = mid - 1
return -1Try it in the online compiler →Checkpoint quiz
Max comparisons for 1,024 sorted items?