typestar

Binary search in JavaScript

Halve the range each step; a thousand items takes ten comparisons.

function binarySearch(items, target) {
  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
247
Tokens
85
Three-star pace
90 tpm

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

Type this snippet

Step 10 of 10 in Arrays, step 26 of 43 in Language basics.

← Previous Next →

Binary search in other languages