← Back to libraryQuestion 95 of 273
⌨️Java CodingBeginner

Binary Search

📌 Definition:

Find the index of a target in a SORTED array in O(log n) by repeatedly halving the search range.

📖 Detailed Explanation:

Maintain low and high bounds; compute mid, compare to the target, and discard the half that cannot contain it. Compute mid as low + (high - low) / 2 to avoid integer overflow. Requires a sorted array. O(log n).

💻 Solutions:
public static int binarySearch(int[] a, int target) {
    int low = 0, high = a.length - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (a[mid] == target) return mid;
        if (a[mid] < target) low = mid + 1; else high = mid - 1;
    }
    return -1;
}
function binarySearch(a, target) {
  let low = 0, high = a.length - 1;
  while (low <= high) {
    const mid = (low + high) >> 1;
    if (a[mid] === target) return mid;
    if (a[mid] < target) low = mid + 1; else high = mid - 1;
  }
  return -1;
}
def binary_search(a, target):
    low, high = 0, len(a) - 1
    while low <= high:
        mid = (low + high) // 2
        if a[mid] == target:
            return mid
        if a[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1
🔑 Key Points:
  • Array must be sorted
  • mid = low + (high - low) / 2 avoids overflow
  • Discard half each step -> O(log n)
  • Return -1 (or insertion point) when absent
🌍 Real-World Example:

Binary search powers lookups in sorted indexes, version bisection (git bisect), and any "find the boundary" search over a monotonic space.

🎯 Scenario-Based Interview Question:

In Java, why prefer mid = low + (high - low)/2 over (low + high)/2?