Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Easy · Free

Implement binary search. What preconditions must hold?

FresherFundamentalsData Structures & Algorithms
Model answer

Binary search

Requires sorted array. Repeatedly halve search space comparing mid to target—O(log n).

java
int binarySearch(int[] a, int target) {
  int lo = 0, hi = a.length - 1;
  while (lo <= hi) {
    int mid = lo + (hi - lo) / 2;
    if (a[mid] == target) return mid;
    if (a[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return -1;
}
Use mid = lo + (hi-lo)/2 to avoid overflow—small detail seniors notice.