typestar

Binary search in TypeScript

Binary search over a sorted array, generic in the element type.

function binarySearch(items: number[], target: number): number {
  let lo = 0;
  let hi = items.length - 1;
  while (lo <= hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (items[mid] === target) return mid;
    if (items[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return -1;
}

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
273
Tokens
93
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 53 seconds.

Type this snippet

Step 10 of 11 in Generic helpers, step 18 of 20 in Generics.

← Previous Next →

Binary search in other languages