A foundational $O(\log n)$ search algorithm for sorted arrays.
The original problem is here.
Binary search is effectively an inward-traversal two-pointer technique!
left) to track the start of our active search space.right) to track the end of our active search space.mid pointer.target value with the value at nums[mid]: mid value, we found it!mid value, it must exist in the right half of the remaining array. We update left = mid + 1.mid value, it must exist in the left half of the remaining array. We update right = mid - 1.left pointer crosses the right pointer (left > right).mid value, the next situation is left>right.left > right, it means our search space has collapsed completely and the target element is absolutely not in the array. We return -1.class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
# Target not found
return -1
left, right, and mid) which require constant memory.while loop, we halve the size of the search array. Consequently, the maximum number of times the loop can run is proportional to the base-2 logarithm of $n$.