Binary Search
Binary search finds a target in a sorted array by repeatedly discarding half of the remaining range. It is O(log n) time and O(1) extra space.
Detailed Explanation
Linear search asks includes and walks every element. If the array is already sorted, you can do better. Look at the middle. If it is the target, stop. If the target is smaller, the answer (if it exists) is on the left. If larger, on the right. Each step halves the interval.
The loop maintains lo and hi as a half-open or closed range. Off-by-one errors live here. A robust closed-range version:
while (lo <= hi) {
const mid = lo + ((hi - lo) >> 1);
// compare arr[mid] to target, then hi = mid - 1 or lo = mid + 1
}
lo + ((hi - lo) >> 1) avoids overflow in languages where lo + hi overflows; in JavaScript numbers are doubles, so overflow is not the issue, but the form is still the one to write. Do not write Math.floor((lo + hi) / 2) as a habit you drop when you switch to another language.
The array must be sorted in the same order you compare. An unsorted array makes binary search return nonsense without throwing. If you sort first, the total cost is O(n log n), which is worse than a linear scan for a single lookup. Binary search pays off when you search many times, or when the array is already sorted (dates, ids, a timeline).
Variants: lower bound (first index >= target), upper bound (first index > target), search on an answer space ("smallest capacity that ships in D days") where arr[mid] is replaced by a predicate feasible(mid). The last is often called binary search on the answer.
Array.prototype has no binary search. You write it, or you use a library. indexOf is linear.
What it costs you: a wrong invariant. If you write hi = mid in a closed range you can loop forever. If the comparator and the sort disagree (localeCompare vs <), you miss. Floating-point midpoints are not an issue for integer indexes.
Reach for binary search on a sorted numeric or comparable array, and on monotonic predicates. Reach for a Map when you look up exact keys and do not have a sorted list. Reach for includes when n is tiny.
Code Examples
function binarySearch(arr, target) {
let lo = 0;
let hi = arr.length - 1;
while (lo <= hi) {
const mid = lo + ((hi - lo) >> 1);
if (arr[mid] === target) return mid;
if (arr[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
console.log(binarySearch([1, 3, 4, 8, 10], 8)); // => 3
console.log(binarySearch([1, 3, 4, 8, 10], 2)); // => -1function lowerBound(arr, target) {
let lo = 0;
let hi = arr.length; // first index whose value is >= target
while (lo < hi) {
const mid = lo + ((hi - lo) >> 1);
if (arr[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
console.log(lowerBound([1, 3, 3, 8], 3)); // => 1Common Gotchas
The input must be sorted in the same order as the comparator
an unsorted list does not throw; it just returns the wrong index.
Off-by-one loops forever
pick closed (`lo <= hi`, `hi = mid - 1`) or half-open (`lo < hi`, `hi = mid`) and stay consistent.
Sorting then searching once is slower than a scan
O(n log n) vs O(n). Binary search is for repeated queries or already-sorted data.
Duplicate values
exact search may return any match. Use lower/upper bound when you need the first or last.