Statement▼
We are given an array of integers, nums, sorted in ascending order, and an integer value, target. If the target exists in the array, return its index. If the target does not exist, return -1.
Constraints:
1 ≤ nums.length≤ 103 −104 ≤ nums[i],target≤ 104 All integers in
numsare unique.numsis sorted in ascending order.
Solution
Binary search locates a target value in a sorted array by repeatedly dividing the search space in half. We compare the target with the middle element, starting with the entire array. If they match, we return the index. If the target is smaller, we narrow the search to the left half; if larger, we search the right half. This process continues until the target is found or the search space is exhausted.
We can solve the above problem using the iterative approach by following the steps below:
Initialize
lowto 0 andhightonums.length - 1.While
lowis less than or equal tohigh:Compute
midusing the formulamid=low+((high−low)/2) If
nums[mid]is equal to the target, returnmid.If
nums[mid]is greater than the target, updatehigh = mid - 1to search in the left half.If
nums[mid]is less than the target, updatelow = mid + 1to search in the right half.
Repeat the process by recalculating
midin each iteration.
If
lowbecomes greater thanhigh, return-1, indicating that the target is not in the array because the algorithm has checked all the positions where the target could be.
Let’s look at the following illustration to get a better understanding of the algorithm: