Full answer
Binary search finds a value in a sorted array in O(log n) steps. At each step, look at the middle element. If it equals the target, you are done. If the target is smaller, discard the right half. If it is larger, discard the left half.
Most bugs come from unclear bounds. Pick one convention and keep it. A safe one is the half-open range [left, right): start with left = 0 and right = array.length, loop while (left < right), compute mid = left + Math.floor((right - left) / 2), then move left = mid + 1 or right = mid. In JavaScript, integers do not overflow the way they do in other languages, so (left + right) / 2 is safe, but you still need Math.floor, and the left + (right - left) / 2 habit is good practice.
The most useful version is the lower bound: the first index whose value is not less than the target. The loop keeps the invariant that everything before left is smaller than the target and everything from right on is not smaller. When the loop ends, left is the first occurrence if it exists, or the position where the target should be inserted to keep the array sorted. The upper bound is the same with <=. The count of a value is upper - lower.
Binary search is also a technique for answers, not only for arrays: find the smallest value of a number for which a condition is true, as long as the condition is monotonic (false, false, true, true). Examples are integer square root and the smallest capacity that ships packages in D days.
Pitfalls: unsorted input, a comparator that does not match the sort order, an infinite loop caused by left = mid without progress, and sorting strings with the default sort when numbers are meant. Note that Array.prototype.indexOf is O(n), and includes too, so for repeated lookups on large data, sort once and use binary search, or use a Set.
function lowerBound(sorted, target) {
let left = 0;
let right = sorted.length;
while (left < right) {
const mid = left + Math.floor((right - left) / 2);
if (sorted[mid] < target) left = mid + 1;
else right = mid;
}
return left;
}
function upperBound(sorted, target) {
let left = 0;
let right = sorted.length;
while (left < right) {
const mid = left + Math.floor((right - left) / 2);
if (sorted[mid] <= target) left = mid + 1;
else right = mid;
}
return left;
}
function binarySearch(sorted, target) {
const index = lowerBound(sorted, target);
return index < sorted.length && sorted[index] === target ? index : -1;
}
function integerSqrt(n) {
let left = 0;
let right = n + 1; // first x with x * x > n is in [0, n + 1]
while (left < right) {
const mid = left + Math.floor((right - left) / 2);
if (mid * mid <= n) left = mid + 1;
else right = mid;
}
return left - 1;
}
const data = [1, 3, 3, 3, 5, 8, 13];
console.log(binarySearch(data, 8), binarySearch(data, 4), binarySearch([], 1));
console.log('first 3 at', lowerBound(data, 3), 'count of 3:', upperBound(data, 3) - lowerBound(data, 3));
console.log('insert 4 at', lowerBound(data, 4), 'insert 0 at', lowerBound(data, 0), 'insert 99 at', lowerBound(data, 99));
console.log([0, 1, 15, 16, 17, 99, 100].map((n) => integerSqrt(n)));
// check against the built-in on many cases
let ok = true;
for (let length = 0; length < 30; length++) {
const array = Array.from({ length }, (_, i) => Math.floor(i / 2));
for (let target = -1; target <= length; target++) {
if (binarySearch(array, target) !== -1 !== array.includes(target)) ok = false;
if (lowerBound(array, target) !== array.findIndex((x) => x >= target) && array.some((x) => x >= target)) ok = false;
}
}
console.log('agrees with includes and findIndex:', ok);
console.log([10, 9, 1].sort(), [10, 9, 1].sort((a, b) => a - b));Run with Node.js v24.22.1 as js-121.js; two runs gave identical output. Output: 5 -1 -1 first 3 at 1 count of 3: 3 insert 4 at 4 insert 0 at 0 insert 99 at 7 [ 0, 1, 3, 4, 4, 9, 10 ] agrees with includes and findIndex: true [ 1, 10, 9 ] [ 1, 9, 10 ]
Key points
- Halve a sorted range each step for O(log n); input must be sorted.
- Use one clear bounds convention, such as half-open [left, right).
- Lower bound gives the first occurrence or insertion index; upper bound minus lower bound gives the count.
- It also works on monotonic conditions, such as integer square root.
- Avoid infinite loops: always move left to mid plus 1 or right to mid.
Common mistakes
- Running binary search on unsorted data or on numbers sorted as strings.
- Mixing bound conventions, which gives off-by-one errors and infinite loops.
- Returning the first match found, when the first occurrence is needed.
- Using indexOf in a loop on large arrays instead of sorting once.
Follow-ups
- How would you search in a rotated sorted array?
- How does the lower bound help to insert into a sorted array?
- How would you apply binary search to find the smallest valid value of a condition?
Tips
- State the bounds convention and the loop invariant before coding.
- Use lower bound as the base for first occurrence, insertion, and count.
- Mention that it also works on monotonic conditions.