Sub topic 10
Binary Search on Sorted Arrays
This chapter assumes you can write comparator functions, know that the default sort() compares elements as strings, and have used linear search methods such as indexOf and includes.
Methods like indexOf and find check elements one at a time. On an array of a million items, a miss can take a million comparisons. If the array is already sorted, you can do much better. Binary search finds an element, or proves it is absent, in about 20 comparisons for a million items.
How Binary Search Works
Binary search keeps track of a range of positions where the target could still be. On each step it looks at the middle element of that range:
- If the middle element equals the target, the search is done.
- If the middle element is smaller, the target can only be in the right half.
- If it is larger, the target can only be in the left half.
Each step throws away half of the remaining range. That halving is why the running time is O(log n) and not O(n).
A Reusable 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 takes the same kind of comparator that sort uses, so it works for strings, dates, and objects as well as numbers. The expression (lo + hi) >>> 1 is an integer midpoint. The unsigned right shift divides by two and drops the fraction in one step.
The Precondition: Sorted With the Same Comparator
Binary search gives no warning when its input is wrong. It just returns wrong answers. The array must meet two conditions:
- It is sorted.
- It was sorted with the same ordering that you pass to the search.
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;
}
// Unsorted input: 8 is at index 0, but the search misses it.
console.log(binarySearch([8, 2, 23, 5], 8)); // -1
// Sorted with the default string order, searched numerically.
const wrongOrder = [1, 5, 10, 100].sort(); // [1, 10, 100, 5]
console.log(binarySearch(wrongOrder, 5)); // -1Searching Objects by Key
To search objects, write a comparator that compares the key of an element against the target. The array must be sorted by that same key.
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: 7, name: 'Bo' },
{ id: 12, name: 'Cy' }
];
const i = binarySearch(users, 7, (user, id) => user.id - id);
console.log(users[i].name); // 'Bo'Here the comparator's second argument is a plain id, not a user object. That is fine, because the function only has to report whether the element comes before, after, or at the target.
Finding the Insertion Point
A common variant returns the first index whose element is not less than the target. This is often called the lower bound. It tells you where to insert a new value so the array stays sorted.
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;
}
const data = [2, 5, 8, 12, 23, 38];
const pos = lowerBound(data, 7);
console.log(pos); // 2
data.splice(pos, 0, 7);
console.log(data); // [2, 5, 7, 8, 12, 23, 38]When the array has duplicates, lowerBound always returns the first one. The plain binarySearch returns whichever matching element it reaches first.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Searching an unsorted array | Elements that exist are reported as missing | Sort first, or use `indexOf` or `find` |
| Sort and search comparators differ | Wrong or inconsistent results | Pass the same comparator to both |
| `hi = mid` with `lo <= hi` | Infinite loop | Pair `lo <= hi` with `hi = mid - 1`, or `lo < hi` with `hi = mid` |
| Sorting before every search | Slower than a linear scan | Sort once, then search many times |
Exercise
About how many comparisons does binary search need, in the worst case, on a sorted array of 1,000,000 elements? How many does indexOf need when the value is missing?
Show answer
About 20, because 2^20 is roughly 1,048,576 and each step halves the range. indexOf compares against all 1,000,000 elements before it returns -1.
Exercise
An array of product objects is sorted with (a, b) => a.price - b.price. Write a binarySearch call that finds the index of a product priced 19.99.
Show answer
binarySearch(products, 19.99, (p, price) => p.price - price). The comparator orders by price, which matches the order used to sort the array. If several products cost 19.99, the call returns any one of their indexes, so use lowerBound to get the first.