AlgoPlusAlgoPlus
Learn/Data Structures & Algorithms
Lesson

Binary Search

Find a target in a sorted array by halving the search window every step — O(log n).

7 min read Watch it move Build it

Binary search finds a value in a sorted array by repeatedly looking at the middle element and throwing away the half that can't contain the target. Each step halves the work, so even a million elements take only ~20 comparisons.

Precondition: the array must be sorted
Binary search relies on order to decide which half to discard. On an unsorted array it gives wrong answers — sort first (or use linear search).

The loop, step by step

  1. 1Track a window with lo and hi (start: the whole array).
  2. 2Look at the middle: mid = (lo + hi) / 2.
  3. 3If arr[mid] equals the target → found.
  4. 4If arr[mid] is less than the target → the answer is to the right, so lo = mid + 1.
  5. 5If arr[mid] is greater → the answer is to the left, so hi = mid - 1.
  6. 6Repeat until found or the window is empty (lo > hi).
function binarySearch(arr, target) {
  let lo = 0, hi = arr.length - 1;
  while (lo <= hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (arr[mid] === target) return mid;
    if (arr[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return -1; // not found
}
OperationTimeSpace
Search · halves the window each stepO(log n)O(1)
Check yourself
Why can binary search discard half the array each step?