πŸ” What is Binary Search?

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.

πŸ“Œ Pre-condition:


🧠 How It Works (Intuition)

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.


βœ… Basic Binary Search (Iterative)

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
}

πŸ”’ Example:

nums = [1, 3, 5, 7, 9], target = 5 β†’ Output: 2

🧰 Step-by-Step Walkthrough

Input:

nums = [2, 4, 7, 10, 14, 19], target = 10

Steps:

  1. left = 0, right = 5
  2. mid = 2, nums[2] = 7 β†’ 7 < 10 β†’ move left = mid + 1 = 3
  3. mid = 4, nums[4] = 14 β†’ 14 > 10 β†’ move right = mid - 1 = 3