Binary search
Find a target in sorted data by ruling out half of the remaining values at each step.
left, right = 0, len(values) - 1while left <= right: mid = (left + right) // 2 if values[mid] == target: return mid if values[mid] < target: left = mid + 1 else: right = mid - 1return -1Start with the entire sorted array.
Keep a range of possible answers
Binary search requires sorted data. The search range starts at left = 0 and right = length - 1. Choose the middle index and compare that value with the target. If the middle value is too small, every value to its left is also too small. Move left beyond the midpoint to discard those candidates.
How it works
Write down the range after each comparison. For target 12, the first candidate is 9. Everything to its left is at most 9, so keep only indexes 3 through 4. The next candidate is 12. For a missing target, keep making the same reductions until the left boundary passes the right boundary.
Trace the boundaries
Look for 12 in [2, 5, 9, 12, 20]. The first middle index is 2, where the value is 9. Keep indices 3 through 4 and check the new midpoint, index 3. When the target is absent, the bounds cross and the loop ends. An empty array starts with crossed bounds.
Explain the cost and the result
Each step shrinks the remaining range by roughly half, so the worst-case time is O(log n). The iterative version holds a fixed number of variables and uses O(1) additional space. For duplicates, this version returns any matching index. Finding the first match calls for a different boundary update.
Code example
def binary_search(values, target):
left, right = 0, len(values) - 1
while left <= right:
middle = left + (right - left) // 2
if values[middle] == target:
return middle
if values[middle] < target:
left = middle + 1
else:
right = middle - 1
return -1
print(binary_search([2, 5, 9, 12, 20], 12))Check your understanding
A library shelf displays sorted copy numbers. Return the zero-based index of a requested number, or -1 if the copy is absent.
See the example and explanation
- Last copy
- Given
[3, 8, 11, 19], target = 19 - Answer
3 - Missing copy
- Given
[3, 8, 11, 19], target = 10 - Answer
-1 - Empty shelf
- Given
[], target = 3 - Answer
-1
Searching for 19 examines 8, then 11, then 19 at index 3. Searching for 10 examines 8, then 11. Both selected midpoints are discarded, leaving an empty range. An empty shelf has no candidates from the beginning.