Binary Search is a search algorithm used to find the position of a target value in a sorted array. It repeatedly divides the search interval in half.
Imagine you're guessing a number between 1 and 100. Each time, you ask if the number is higher or lower. Youβre cutting the range in half β this is binary search in action.
public int binarySearch(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // Avoid overflow
if (nums[mid] == target)
return mid;
else if (nums[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return -1; // Not found
}
nums = [1, 3, 5, 7, 9], target = 5 β Output: 2
nums = [2, 4, 7, 10, 14, 19], target = 10
left = 0
, right = 5
mid = 2
, nums[2] = 7
β 7 < 10 β move left = mid + 1 = 3
mid = 4
, nums[4] = 14
β 14 > 10 β move right = mid - 1 = 3