Split the search in half
You are looking for one name in a phone book sorted from A to Z. Reading every entry works, but you can do better. Open the book in the middle: if the name you want comes after that page, everything before it is irrelevant. You have thrown away half the book, and the task is exactly the same on what is left.
That is divide and conquer. Each step splits the search space in half and keeps only the half that can still hold the answer, so the problem shrinks fast instead of one item at a time.
Name the case that stops. When the window between your lowest and highest index is empty, the name is not on any page, so you report that it is missing. That is the base case, and it answers without another split.
Shrink the input by moving the low or the high edge past the middle, depending on which half the target falls in. Then trust the call: assume the search on the smaller window already returns the right index, and pass that answer back.
function binarySearch(list, target) {
function search(low, high) {
if (low > high) {
return -1;
}
const mid = Math.floor((low + high) / 2);
if (list[mid] === target) {
return mid;
}
return list[mid] < target ? search(mid + 1, high) : search(low, mid - 1);
}
return search(0, list.length - 1);
}
Each split halves the window, so a book of a thousand pages is found in about ten steps.
Export binarySearch from index.js. It returns the index of the target in a
sorted list, or -1 when the value is not there.
Challenge
A phone book is sorted, so you never read it from start to finish. Export a
binarySearch function from index.js that finds a value by halving the
search space.
binarySearch takes a sorted array and a target value. It returns the index of
the target, or -1 when the target is absent. Compare against the middle of the
current window and recurse into only the half that can still contain the target.