Implement Binary Search
Write a function that, given a sorted array of integers and a target value, returns the index of the target, or -1 if not found.
Requirements
- Time complexity: O(log n)
- Space complexity: O(1) (iterative solution)
- Array is sorted in ascending order, no duplicates
Hints
- Set
low = 0andhigh = len(nums) - 1. - Compute
mid = (low + high) // 2. - If
nums[mid] == target, returnmid. - If
nums[mid] < target, setlow = mid + 1. Ifnums[mid] > target, sethigh = mid - 1. - Repeat until
low > high.
The key gotcha: you must adjust low or high to mid + 1 or mid - 1 (not just mid) to avoid infinite loops.