It only works on a sorted list#

The middle tells you which side to throw away only because everything to its left is smaller. Shuffle the same numbers and that promise breaks.

3458913212551448012345678
The same numbers, shuffled

Quick check

Quick check: The middle is 21. It is smaller than 34, so binary search throws away the left side. Does it find 34?

The code#

This is the run you just watched, as code. low and high mark the part still in play. Slide the target to 40, a number that is not in the list, and watch low pass high.

Binary search, line by lineline 1
Try another target
  1. nums = [2, 5, 8, 13, 21, 34, 55, 89, 144]
  2. target = 34
  3. low, high = 0, len(nums) - 1
  4. answer = -1
  5. while low <= high:
  6. mid = (low + high) // 2
  7. if nums[mid] == target:
  8. answer = mid
  9. break
  10. elif nums[mid] < target:
  11. low = mid + 1
  12. else:
  13. high = mid - 1
  14. print(answer)

Variables

nums

2581321345589144

Nine numbers, already sorted.

Step 1 of 20

The same function in Python, C++, C, Java and Go:

How few looks it needs#

Every look throws away half of what is left, so even a huge list runs out fast.

Quick check

Quick check: A sorted list holds 10 lakh roll numbers. At most how many looks does binary search need?

Binary Search on the Answer#

The trick generalizes further than "find a value in a sorted array". Any time a yes/no question gets easier as you raise the number you're asking about, that monotonic yes/no boundary is itself something you can binary search, even when nothing is stored in an array at all.

The classic example: stations sit along a road at positions [0, 6, 10, 20], and you may add k = 4 new stations anywhere you like. How small can you make the largest gap between neighbours?

The answer is a distance, not an index. So we binary search the distance: pick a candidate d, ask "can 4 extra stations bring every gap under d?" (a simple sum of ceil(gap / d) - 1), and move lo or hi depending on the verdict.

In the visualization below, watch the lo/hi/mid panel at the top: a green mid means the candidate distance is achievable, so hi shrinks toward it; a red mid means it needs more than 4 stations, so lo rises. The interval keeps halving until it pins the answer at roughly 3.33.

Visualizer

Min Max Gas Station

Open full →

What to remember#

  • Binary search needs a sorted list, or any yes/no question whose answer flips once along a line.
  • low and high mark what is still in play. Look at the middle, drop the half that cannot hold the target, and stop when low passes high.
  • O(log n) time and O(1) extra space.