Question:
https://leetcode.com/problems/binary-search/
We are given a sorted array of integers nums (ascending order).
Write a function that searches for target in nums.
- If
targetexists, return its index - Otherwise, return
-1 - The algorithm must run in O(log n) time
Because the array is sorted, we can use binary search.
Instead of scanning both halves, we:
- Repeatedly discard half of the search space
- Compare the middle element to the target
- Narrow the search range accordingly
- Set two pointers:
lowandhigh - While
low <= high:- Compute
mid - If
nums[mid] == target, returnmid - If
nums[mid] < target, search the right half - Otherwise, search the left half
- Compute
- If the loop ends, the target is not present → return
-1
- time O(log n)
- space O(1)
func search(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + (high - low)/2
if nums[mid] == target {
return mid
}
if nums[mid] > target{
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}