Binary Search With Boundaries

Search a sorted array in logarithmic time, returning the index of a match or the insertion point when the value is absent.

JavascriptData Integrity

Code

javascriptsnippet
15 lines
export function binarySearch(sorted, target, compare = (a, b) => a - b) {
  let low = 0;
  let high = sorted.length;
  while (low < high) {
    const mid = (low + high) >>> 1;
    const cmp = compare(sorted[mid], target);
    if (cmp < 0) {
      low = mid + 1;
    } else {
      high = mid;
    }
  }
  const found = low < sorted.length && compare(sorted[low], target) === 0;
  return { index: low, found };
}

How it works

The working surface is the functions mid and binarySearch — everything else is wiring.

Repetition is confined to while (low < high) — the rest of the file is straight-line.

The result comes back as an object carrying low.

Putting it to use

The primary signature is export function binarySearch(sorted, target, compare = (a, b)

Import binarySearch from the file and call it — the rest of the code is implementation detail.

The call returns low.

Core lines

return { index: low, found };

Interactive Tools for This Topic

FAQ

Does `binarySearch` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `mid`, `binarySearch` at load time.