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.
Code
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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.