1. The idea
Because the list is sorted, one comparison with the middle value tells you which half the target must be in. Throw away the other half and repeat. Each step halves the work, which is what makes binary search a divide and conquer algorithm.
2. Tracing the loop
- Start with the whole list:
left = 0andright = len(nums) - 1. - Find the middle:
middle = left + (right - left) // 2. - Compare:
- Equal to the target? Return
middle. - Smaller than the target? The answer is further right, so move
lefttomiddle + 1. - Larger than the target? The answer is further left, so move
righttomiddle - 1.
- Equal to the target? Return
- Stop when the range is empty: once
left > right, the target isn't there, so return-1.
Searching for 56 in the example list checks 48 first (too small), then 71 (too big), then 56: three comparisons instead of five.
3. How fast is it?
- Time: O(1) if the middle element is the target straight away, and O(log n) on average and in the worst case, because the range halves every pass.
- Space: O(1) for this loop version. A recursive version uses O(log n) because each call adds a frame to the call stack.