Skip to content

Binary Search

Lesson 2 of 8 · 5 min

Binary Search

Step 1 of 7

The array is sorted, so the middle element tells you which half the target cannot be in.

The Idea

On sorted data, compare the target with the middle element and throw away the half that cannot contain it. Repeat until one candidate remains. That halving gives you O(log n).

Real-World Example

Finding "Nadia" in your phone contacts. You never scroll from A; you jump near the middle, land somewhere around M, and instantly ignore everything before it. Two or three jumps later you are there.

The Code

Your turn

Fill in the blank.

nums = [1, 3, 5, 7, 9]
lo, hi = 0, 4
mid = (lo + hi) // 2
# nums[mid] is 5 and the target is 9 -> search right
lo = ___

Mini quiz

1 / 3

Binary search requires the input to be: