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

  1. low = 0, high = last index
  2. low ≤ high?
  3. mid = (low + high) // 2
  4. nums[mid] == target?
  5. nums[mid] < target?
  6. low = mid + 1
  7. high = mid − 1
  8. Return mid
  9. Return −1

← All practice problems

Try AI Flowchart free →