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.
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.
target- nums = [2, 5, 8, 13, 21, 34, 55, 89, 144]
- target = 34
- low, high = 0, len(nums) - 1
- answer = -1
- while low <= high:
- mid = (low + high) // 2
- if nums[mid] == target:
- answer = mid
- break
- elif nums[mid] < target:
- low = mid + 1
- else:
- high = mid - 1
- print(answer)
Variables
nums
Nine numbers, already sorted.
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.
What to remember#
- Binary search needs a sorted list, or any yes/no question whose answer flips once along a line.
lowandhighmark what is still in play. Look at the middle, drop the half that cannot hold the target, and stop whenlowpasseshigh.- O(log n) time and O(1) extra space.