Binary search
nums is sorted from small to large. Return the position of target in nums, or -1 if it is not there. Halve the part you search each time instead of checking every number.
Write binary_search(nums, target) in Python, binarySearch(nums, target) in JavaScript or TypeScript, or int binary_search(int nums[], int n, int target) in C. Level: Medium.
Examples
Input: nums = [1, 3, 5, 7, 9, 11], target = 7 Output: 3
Input: nums = [1, 3, 5, 7, 9, 11], target = 4 Output: -1
- 0 ≤ length of nums ≤ 100,000
- All numbers are different
Hint
Keep low and high. Look at mid = (low + high) // 2: if it is too small, move low to mid + 1; too big, move high to mid − 1. Stop when low > high.
The approach, step by step
- low = 0, high = last index
- low ≤ high?
- mid = (low + high) // 2
- nums[mid] == target?
- nums[mid] < target?
- low = mid + 1
- high = mid − 1
- Return mid
- Return −1