Sub topic 10
Binary Search on Sorted Arrays
This chapter assumes you can write comparator functions (covered earlier in this tutorial), you know that indexOf and find scan an array from one end, and you are comfortable with while loops and integer index arithmetic.
The earlier search methods all work by checking elements one at a time until they find a match. That works on any array, sorted or not. When an array is already sorted, you can do much better. Binary search uses the ordering to throw away half of the remaining candidates on every comparison. For a million elements, a linear scan may need a million comparisons, and binary search needs about twenty.
The Core Idea
Binary search keeps track of a range of indexes where the target could still be. On each step it looks at the middle element of that range and compares it to the target:
- If the middle element equals the target, the search is done.
- If the middle element is smaller than the target, the target can only be to the right, so the left half is discarded.
- If the middle element is larger than the target, the target can only be to the left, so the right half is discarded.
When the range becomes empty, the target is not in the array.
A Reference Implementation
function binarySearch(sorted, target, compare = (a, b) => a - b) {
let lo = 0;
let hi = sorted.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >>> 1;
const c = compare(sorted[mid], target);
if (c === 0) return mid;
if (c < 0) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
const data = [2, 5, 8, 12, 23, 38];
console.log(binarySearch(data, 23)); // 4
console.log(binarySearch(data, 7)); // -1The function follows the same comparator contract as sort: compare(a, b) returns a negative number when a comes before b, zero when they are equivalent, and a positive number when a comes after b. The return value matches indexOf: an index on success, -1 on failure.
Tracing the Two Calls
Searching for 23 in [2, 5, 8, 12, 23, 38]:
| Step | lo | hi | mid | sorted[mid] | Comparison | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | 8 | 8 < 23 | lo = 3 |
| 2 | 3 | 5 | 4 | 23 | equal | return 4 |
Searching for 7:
| Step | lo | hi | mid | sorted[mid] | Comparison | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | 8 | 8 > 7 | hi = 1 |
| 2 | 0 | 1 | 0 | 2 | 2 < 7 | lo = 1 |
| 3 | 1 | 1 | 1 | 5 | 5 < 7 | lo = 2 |
| 4 | 2 | 1 | — | — | lo > hi | return -1 |
The loop ends in step 4 because the range is empty. Notice where lo stopped: index 2, which is exactly where 7 would need to be inserted to keep the array sorted. This fact comes back later in the chapter.
The Loop Invariant
To understand why the code is correct, and to avoid off-by-one bugs when you change it, keep one statement in mind: if the target is in the array at all, its index is between lo and hi, inclusive. This statement is called the loop invariant.
- At the start,
lo = 0andhi = length - 1cover the whole array, so the invariant holds. - Setting
lo = mid + 1is safe becausesorted[mid]and everything to its left are smaller than the target. - Setting
hi = mid - 1is safe becausesorted[mid]and everything to its right are larger. - Because each step excludes
miditself, the range shrinks every time, so the loop always ends.
Most broken binary searches violate one of these points. Writing lo = mid instead of lo = mid + 1 with an inclusive hi can loop forever when lo and hi are adjacent, because mid rounds down to lo and the range never shrinks.
Computing the Midpoint
(lo + hi) >>> 1 is an unsigned right shift by one bit, which divides by two and drops the fraction. It is equivalent to Math.floor((lo + hi) / 2) for valid array indexes. You must use one of the two. Plain (lo + hi) / 2 yields 2.5, and sorted[2.5] is undefined.
In languages with 32-bit integers, lo + hi can overflow on huge arrays, which is why you often see lo + ((hi - lo) >> 1). JavaScript numbers do not overflow at that size, but >>> converts its operand to a 32-bit unsigned integer, so it would give wrong results if lo + hi reached 2^32. That only happens with arrays of more than about two billion elements, so in practice either form is fine.
The Precondition: Sorted With the Same Comparator
Binary search has one requirement that the code cannot check cheaply: the array must be sorted in the order that the search comparator describes. "Sorted" by itself is not enough. It has to be sorted by the same rule.
The most common way to break this is to sort with the default string ordering and then search numerically:
function binarySearch(sorted, target, compare = (a, b) => a - b) {
let lo = 0;
let hi = sorted.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >>> 1;
const c = compare(sorted[mid], target);
if (c === 0) return mid;
if (c < 0) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
const nums = [10, 1, 5, 100];
nums.sort(); // string order: [1, 10, 100, 5]
console.log(binarySearch(nums, 5)); // -1, although 5 is present
nums.sort((a, b) => a - b); // numeric order: [1, 5, 10, 100]
console.log(binarySearch(nums, 5)); // 1On the string-sorted array, the search compares 10 with 5, decides 5 must be to the left, and never looks at index 3. There is no error. You just get a wrong answer.
Other ways to break the precondition:
- Sorting descending, searching ascending. If you sorted with
(a, b) => b - a, you must search with the same comparator. - Mutating after sorting. Pushing a new element onto the end, or changing a property used as the sort key, makes the array unsorted again.
- Inconsistent comparators. A comparator that returns
NaN, for examplea - bwhen the array containsNaNorundefined, makes every comparison look "not less than zero", and the search drifts left.sortmovesundefinedto the end without calling the comparator, but the search will still call it on them. - Mixed locales or options for strings. An array sorted with
localeComparein one locale may be out of order for a collator with different options.
Checking sortedness takes O(n) time, which cancels the benefit of searching in O(log n). Put such checks in tests or debug builds, not in the hot path.
function isSortedBy(arr, compare) {
for (let i = 1; i < arr.length; i++) {
if (compare(arr[i - 1], arr[i]) > 0) return false;
}
return true;
}
console.log(isSortedBy([1, 10, 100, 5], (a, b) => a - b)); // false
console.log(isSortedBy([1, 5, 10, 100], (a, b) => a - b)); // trueSearching Objects and Strings
Because the comparator is called as compare(sorted[mid], target), the target does not have to be the same kind of value as the elements. This lets you search an array of objects by a key without building a fake object:
function binarySearch(sorted, target, compare = (a, b) => a - b) {
let lo = 0;
let hi = sorted.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >>> 1;
const c = compare(sorted[mid], target);
if (c === 0) return mid;
if (c < 0) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
const users = [
{ id: 3, name: 'Ana' },
{ id: 8, name: 'Bo' },
{ id: 15, name: 'Cy' },
{ id: 42, name: 'Di' }
];
const byIdToKey = (user, id) => user.id - id;
const i = binarySearch(users, 15, byIdToKey);
console.log(i, users[i].name); // 2 'Cy'The array must be sorted by id ascending, which matches (a, b) => a.id - b.id.
For strings shown to people, sort and search with the same Intl.Collator:
function binarySearch(sorted, target, compare = (a, b) => a - b) {
let lo = 0;
let hi = sorted.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >>> 1;
const c = compare(sorted[mid], target);
if (c === 0) return mid;
if (c < 0) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
const collator = new Intl.Collator('en', { numeric: true });
const files = ['item10', 'item2', 'item1', 'item21'].sort(collator.compare);
console.log(files); // ['item1', 'item2', 'item10', 'item21']
console.log(binarySearch(files, 'item10', collator.compare)); // 2The collator may treat strings as equal that === does not, for example with sensitivity: 'base', where 'a' and 'A' compare as equal. In that case binary search finds a collation-equal element, which may not be the exact string you passed.
Duplicates and Insertion Points: Lower and Upper Bound
The basic version returns some matching index. With duplicates, that could be any of them:
function binarySearch(sorted, target, compare = (a, b) => a - b) {
let lo = 0;
let hi = sorted.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >>> 1;
const c = compare(sorted[mid], target);
if (c === 0) return mid;
if (c < 0) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
console.log(binarySearch([1, 4, 4, 4, 4, 9], 4)); // 2, not the first 4 at index 1When you need the first match, the last match, or the position where a missing value belongs, use the bound variants. They use a half-open range [lo, hi), where hi is one past the last candidate, and they never stop early on equality.
// First index whose element is not less than target.
function lowerBound(sorted, target, compare = (a, b) => a - b) {
let lo = 0;
let hi = sorted.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (compare(sorted[mid], target) < 0) lo = mid + 1;
else hi = mid;
}
return lo;
}
// First index whose element is greater than target.
function upperBound(sorted, target, compare = (a, b) => a - b) {
let lo = 0;
let hi = sorted.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (compare(sorted[mid], target) <= 0) lo = mid + 1;
else hi = mid;
}
return lo;
}
const arr = [1, 4, 4, 4, 4, 9];
console.log(lowerBound(arr, 4)); // 1, first 4
console.log(upperBound(arr, 4) - 1); // 4, last 4
console.log(upperBound(arr, 4) - lowerBound(arr, 4)); // 4 occurrences
console.log(lowerBound(arr, 5)); // 5, where 5 would go
console.log(lowerBound(arr, 100)); // 6, past the endBoth functions always return a number from 0 to length, never -1. To test membership with lowerBound, check both conditions:
function lowerBound(sorted, target, compare = (a, b) => a - b) {
let lo = 0;
let hi = sorted.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (compare(sorted[mid], target) < 0) lo = mid + 1;
else hi = mid;
}
return lo;
}
function contains(sorted, target, compare = (a, b) => a - b) {
const i = lowerBound(sorted, target, compare);
return i < sorted.length && compare(sorted[i], target) === 0;
}
console.log(contains([1, 4, 9], 4)); // true
console.log(contains([1, 4, 9], 5)); // falseHere hi = mid, not mid - 1, is correct because the range is half-open. sorted[mid] might be the answer, so it stays a candidate at the boundary. Mixing the inclusive style (<=, mid - 1) with the half-open style (<, hi = mid) causes most binary search bugs. Pick one style per function and keep it consistent.
Range queries also come for free. All values in [low, high) lie between lowerBound(arr, low) and lowerBound(arr, high), so arr.slice(lowerBound(arr, low), lowerBound(arr, high)) extracts them in O(log n) plus the size of the slice.
Keeping an Array Sorted
lowerBound gives you the insertion point, so you can add values without re-sorting:
function lowerBound(sorted, target, compare = (a, b) => a - b) {
let lo = 0;
let hi = sorted.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (compare(sorted[mid], target) < 0) lo = mid + 1;
else hi = mid;
}
return lo;
}
function insertSorted(sorted, value, compare = (a, b) => a - b) {
sorted.splice(lowerBound(sorted, value, compare), 0, value);
return sorted;
}
const scores = [10, 20, 30];
insertSorted(scores, 25);
insertSorted(scores, 5);
console.log(scores); // [5, 10, 20, 25, 30]Finding the position takes O(log n), but splice still shifts every later element, which is O(n). This is still cheaper than pushing and re-sorting, which costs O(n log n). If you insert heavily and search rarely, a different structure may suit you better. The next chapter covers that choice.
When Binary Search Pays Off
| Situation | Better choice | Reason |
|---|---|---|
| One search on an unsorted array | `indexOf`, `find` | Sorting first costs O(n log n), more than one O(n) scan |
| Many searches on data that rarely changes | Sort once, then binary search | Each search is O(log n) |
| Need nearest value, range, or insertion point | `lowerBound` / `upperBound` | Hash-based structures have no ordering |
| Exact-match lookups only, many of them | `Set` or `Map` (next chapter) | Average O(1) per lookup |
| Small arrays (a few dozen elements) | Linear search | Simpler code, and the speed difference is negligible |
Binary search also needs random access by index. It suits arrays and typed arrays, and it does not suit linked lists or iterators.
Exercise
An array of products is sorted with (a, b) => b.price - a.price (most expensive first). You call binarySearch(products, 50, (p, price) => p.price - price) and get -1, though a product priced 50 exists. Why, and what comparator should you pass?
Show answer
The search comparator describes ascending price order, but the array is sorted in descending order, so every "go left" or "go right" decision is reversed. Pass a comparator that matches the descending sort: (p, price) => price - p.price. Equivalently, keep the sort comparator and the search comparator derived from the same rule.
Exercise
Using lowerBound and upperBound, write a function countInRange(sorted, low, high) that returns how many numbers x in a numerically sorted array satisfy low <= x <= high. What does it return for [1, 3, 3, 5, 8, 13] with low = 3 and high = 8?
Show answer
const countInRange = (sorted, low, high) => upperBound(sorted, high) - lowerBound(sorted, low); lowerBound(arr, 3) is 1 and upperBound(arr, 8) is 5, so the result is 4 (the values 3, 3, 5, 8). Using upperBound for the high end makes the range include high.
Exercise
A teammate changes the binarySearch loop to while (lo <= hi) with lo = mid instead of lo = mid + 1. Find an input that makes it loop forever.
Show answer
Search [1, 2] for 2. With lo = 0 and hi = 1, mid = 0 and sorted[0] = 1 < 2, so lo = mid = 0 again. The range never shrinks. Searching for any value larger than the last element of a two-element array triggers the same loop. With an inclusive hi, both boundary updates must exclude mid.