0
Steps
โ
Left (lo)
โ
Right (hi)
โ
Mid
โ
arr[mid]
โฌ 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
- Initialize
lo = 0,hi = n-1 - Compute
mid = Math.floor((lo + hi) / 2) - If
arr[mid] === target: found! Returnmid - If
arr[mid] < target: target is in right half โlo = mid + 1 - If
arr[mid] > target: target is in left half โhi = mid - 1 - 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