Skip to content

Algorithm

Binary Search Algorithm

Imagine looking up a word in a dictionary. You don't start at page one. You flip to the middle, see if the word comes before or after, and halve your sear...

12 Mar 2024 · 2 min read

Binary Search Algorithm

Imagine looking up a word in a dictionary. You don't start at page one. You flip to the middle, see if the word comes before or after, and halve your search. That's binary search.

What It Does

Binary search finds a target in a sorted array by cutting the search space in half with every step. Instead of checking every element (O(n)), it gets there in O(log n).

For an array of 1 million elements, linear search might take 1 million steps. Binary search takes at most 20.

The Code

Javascript
function binarySearch(arr, target) {
  let left = 0;
  let right = arr.length - 1;

  while (left <= right) {
    const mid = Math.floor((left + right) / 2);

    if (arr[mid] === target) return mid;
    if (arr[mid] < target) left = mid + 1;
    else right = mid - 1;
  }

  return -1;
}

const sorted = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91];
console.log(binarySearch(sorted, 23)); // 5
console.log(binarySearch(sorted, 50)); // -1

How It Works Step by Step

Searching for 23 in [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]:

  1. left=0, right=9, mid=4 → arr[4] is 16 < 23 → search right half
  2. left=5, right=9, mid=7 → arr[7] is 56 > 23 → search left half
  3. left=5, right=6, mid=5 → arr[5] is 23 → found it

Three steps instead of six.

Complexity

  • Time: O(log n) — halving the search space each iteration.
  • Space: O(1) for iterative, O(log n) for recursive (stack frames).

The Catch

Binary search requires a sorted array. If the data isn't sorted, you either sort it first (O(n log n)) or use linear search.

Also, watch out for integer overflow on (left + right) / 2 in languages without arbitrary precision. JavaScript handles it fine, but in C++ or Java you'd want left + Math.floor((right - left) / 2).

The Trade-off

Binary search is fast but rigid — it only works on sorted data. If your data changes frequently, maintaining sort order on every insert might cost more than the search savings. In that case, consider a BST or hash map instead.

Ehsan Gazar helps software engineers take LLM and agent systems from demo to production. He writes about building LLM systems that hold up in production: evals, tracing, RAG, agent architecture and cost control. He teaches the Senior to Staff AI Engineer cohort on Maven, where engineers learn to design and defend these systems.

Go further
Live cohort on Maven

Forward Deployed AI Engineering: From Customer Problem to Production Value

A live Maven cohort for engineers: 10 live 90-minute sessions taking one AI engagement from customer problem to production, ending with eight artefacts and a working slice in your own repo.

January cohort starts Tue 12 Jan 2027, Tue & Thu 6:30pm London. Enrolling now, 20 seats, $1,800.

View the live cohort

Keep reading