1. Algorithmic Principle
Binary search relies on the Divide and Conquer paradigm. Because the input sequence is pre-sorted, we can eliminate half of the remaining elements in each step by comparing the middle element directly against the target value.
2. Step-by-Step Execution Walkthrough
- Boundary Initialization: Set two pointers:
low = 0andhigh = len(nums) - 1. - Midpoint Calculation: Compute
mid = low + (high - low) // 2to avoid overflow in large arrays. - Conditional Comparison:
- If
nums[mid] == target, search completes successfully; returnmid. - If
nums[mid] < target, target lies in the right partition. Narrow range by settinglow = mid + 1. - If
nums[mid] > target, target lies in the left partition. Narrow range by settinghigh = mid - 1.
- If
- Termination Condition: If
low > highwithout finding the target, return-1.
3. Complexity Breakdown
- Time Complexity: Best case O(1), Average & Worst case O(log n) because the search domain is halved with every iteration.
- Space Complexity: O(1) for the iterative implementation; O(log n) for recursive calls due to the call stack frame allocation.