Binary Search

Data Structures & Algorithms · Searching & Sorting · Intermediate · 12 min

Find anything in a sorted list by cutting it in half again and again.

A sorted row of numbers with three markers, lo, mid and hi. Every guess at mid greys out half the row in one go, until lo and hi squeeze down to a single slot.

The idea in everyday words

Guess my number between 1 and 100. Smart players say 50. 'Higher!' → 75. 'Lower!' → 62... You throw away half of the possibilities every guess. 100 numbers need only ~7 guesses. That's binary search.

The rule

Works only on sorted data.

  1. Look at the middle item.
  2. If it's the target → done.
  3. Target smaller → search the left half. Bigger → right half.
  4. Repeat until found or nothing left.

Why it's so fast

1,000,000 items → about 20 steps. That's O(log n). Binary search also works on answers: "What's the smallest speed that finishes the job in time?": guess a speed, check, halve.

Step by step

  1. Setup:

    [1,3,5,7,9,11], target 9. lo=0, hi=5.

  2. mid = 2 → 5:

    5 < 9 → the target can only be to the right. lo = 3.

  3. mid = 4 → 9:

    Found it at index 4! Only 2 looks for 6 items.

  4. Not there? target 8:

    Same start. mid 2 (5 < 8) → lo = 3. mid 4 (9 > 8) → hi = 3. mid 3 (7 < 8) → lo = 4.

  5. lo passes hi:

    lo = 4 > hi = 3, so the range is empty. 8 is missing, and lo = 4 is exactly where it would be inserted.

Code example

def binary_search(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        print("checking index", mid, "value", nums[mid])
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

print(binary_search([1, 3, 5, 7, 9, 11], 9))

Complexity

  • Time: O(log n)
  • Space: O(1)

Interview tips

  • Say 'since it's sorted, I can binary search for O(log n)'.

  • Variants: first/last position, search in rotated array, sqrt(x).

  • Dry-run with a 2-element array to catch off-by-one bugs.

Challenge: Where Would It Go?

Given a sorted list and a target, return its index if found; otherwise return the index where it would be inserted to keep the list sorted.

Example: search_insert([1,3,5,6], 2) → 1

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Searching & Sorting

Previous: Prefix Sums · Next: Sorting: Bubble, Merge & Quick