โ† Back to Index

๐Ÿ” Binary Search

Search ยท O(log n)
0
Steps
โ€”
Left (lo)
โ€”
Right (hi)
โ€”
Mid
โ€”
arr[mid]
Enter a target value and click Search, or use Step to go one step at a time.
โฌ† L = left pointer  |  M = mid (current check)  |  R = right pointer
In range
Mid (checking)
Found!
Excluded

How It Works

Binary search finds a target value in a sorted array by repeatedly halving the search space. Instead of checking every element, it compares the target to the middle element and discards the irrelevant half.

Algorithm Steps

  1. Initialize lo = 0, hi = n-1
  2. Compute mid = Math.floor((lo + hi) / 2)
  3. If arr[mid] === target: found! Return mid
  4. If arr[mid] < target: target is in right half โ†’ lo = mid + 1
  5. If arr[mid] > target: target is in left half โ†’ hi = mid - 1
  6. Repeat until found or lo > hi

Key Code

function* binarySearchGen(arr, target) {
  let lo = 0, hi = arr.length - 1;
  while (lo <= hi) {
    const mid = Math.floor((lo + hi) / 2);
    yield { lo, hi, mid, arr };           // pause here to visualize
    if (arr[mid] === target) {
      yield { lo, hi, mid, found: true };
      return mid;
    } else if (arr[mid] < target) {
      lo = mid + 1;                        // discard left half
    } else {
      hi = mid - 1;                        // discard right half
    }
  }
  yield { notFound: true };
  return -1;
}

Why It's Fast

Each step eliminates half the remaining candidates. An array of 1,000,000 elements needs at most 20 steps (logโ‚‚ 1,000,000 โ‰ˆ 20). Compare that to linear search's worst case of 1,000,000 steps.

Complexity

Best Case
O(1)
Average Case
O(log n)
Worst Case
O(log n)
Space
O(1)
Requirement
Sorted array