Binary Search Variant With Lower Bound (TypeScript)

Find the leftmost position where a sorted array can accept a target using a typed binary search lower bound variant.

TypescriptData Fetching

Code

typescriptsnippet
12 lines
function lowerBound<T>(arr: T[], target: T, cmp: (a: T, b: T) => number): number {
  let lo = 0, hi = arr.length;
  while (lo < hi) {
    const mid = (lo + hi) >>> 1;
    if (cmp(arr[mid], target) < 0) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

const arr = [1, 2, 2, 3, 4, 6];
console.log(lowerBound(arr, 2, (a, b) => a - b));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

1

How the snippet works

Binary Search Variant With Lower Bound (TypeScript) reduces to the functions mid and lowerBound.

Iteration happens inside while (lo < hi) — everything outside it runs once.

Applying it

The main signature reads const mid = (lo + hi)

Statements that matter

function lowerBound<T>(arr: T[], target: T, cmp: (a: T, b: T) => number): number {
  let lo = 0, hi = arr.length;
  while (lo < hi) {
    const mid = (lo + hi) >>> 1;
    if (cmp(arr[mid], target) < 0) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `mid`, `lowerBound` at load time.