AlgoTales · Roadmap

Basic binary search

Beginner · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Binary search finds one item in a sorted list by always checking the middle and throwing away the half that cannot contain it. Because every check halves the work, even a million items need only about twenty looks.

Practical use cases

  • Web app: Customer lookup by order number. In an admin panel, support staff type an order number into a search box. The orders are saved in order-number sequence, so instead of scanning from order 1, the code opens the middle of the list, sees whether the number is higher or lower, and halves again. A list of 100,000 orders is answered in about 17 checks, so the result appears the instant they stop typing.
  • Web app: Which release broke the checkout page?. Your site worked last Friday and fails today, with 64 deployments between. Instead of testing all 64, you redeploy the middle one, see if checkout works, and halve the suspicious range again. In 6 tries you know exactly which deployment introduced the bug.
  • System: git bisect. Git can run this same idea over your commit history. You mark one good and one bad commit, and git keeps checking out the middle commit for you to test, finding the guilty commit in a handful of steps even across thousands of commits.

The story: Guess the Number, Win the Game

Kabir challenged Mira: "I'm thinking of a number between 1 and 1000. You get as many guesses as you need, and I'll only say higher or lower." Mira could have guessed 1, 2, 3... that might take 1000 turns.

Instead she said 500. "Lower." That single answer wiped out half the numbers. 250. "Higher." Wiped out half of what was left. 375... Each guess cut the possibilities in half.

She found the answer in 10 guesses. Not 1000. Even for a billion numbers it takes only about 30. The secret is that the numbers were in order, so every answer tells you which half to throw away. The same trick is how you open a dictionary: you never start at page 1.

How to spot this problem, and where you need it

You have a big list that is already in order and you keep scanning it from the top to find one thing, so the more data you collect, the slower every search feels.

Signs you need it

  • The data is sorted (by id, date, price, name) and you are looping through it with a plain for-loop or in_array() to find one value.
  • The problem says "sorted array" or "find the first value that...", or you can answer "is it too big or too small?" with one check.
  • Search speed is fine with 100 rows in testing but crawls with 100,000 rows in production.

Where to use it in a project

  • Looking up a record by id or timestamp in a large pre-sorted result you already hold in memory.
  • Finding the exact point where behaviour changes, such as the first failing build, first price above a limit, or first date with data.

The solution

Keep the list sorted. Check the middle item. If it is too small, ignore the left half; if too big, ignore the right half. Repeat on what is left until you find the item or nothing remains. Each step discards half, so the number of checks stays tiny.

Payoff: Before: up to 100,000 checks per search. After: about 17. The search box feels instant even as the data grows 10 times.

Explain it like I am 8

Imagine finding a name in a phone book. You do not read every page. You open the middle: "S... I want M, so it must be earlier." Throw away the second half. Open the middle of what is left. In a few tries you are there!

How it works, step by step

  1. The list must be sorted. Without order, the "higher/lower" hint means nothing.
  2. Look at the middle item. Is it the target? Done.
  3. Too small? The target must be to the right, so discard the left half. Too big? Discard the right half.
  4. Repeat on what remains until you find it or nothing is left.

The code in four languages

PHP

<?php
function binarySearch(array $sorted, int $target): int {
    $low = 0;
    $high = count($sorted) - 1;

    while ($low <= $high) {
        $mid = intdiv($low + $high, 2);          // look at the middle
        if ($sorted[$mid] === $target) return $mid;
        if ($sorted[$mid] < $target)   $low  = $mid + 1;   // discard left half
        else                           $high = $mid - 1;   // discard right half
    }
    return -1;                                   // not found
}

echo binarySearch([2, 5, 8, 12, 16, 23, 38, 56], 23);      // 5

JavaScript

function binarySearch(sorted, target) {
  let low = 0;
  let high = sorted.length - 1;

  while (low <= high) {
    const mid = Math.floor((low + high) / 2);    // look at the middle
    if (sorted[mid] === target) return mid;
    if (sorted[mid] < target) low = mid + 1;     // discard left half
    else high = mid - 1;                         // discard right half
  }
  return -1;                                     // not found
}

console.log(binarySearch([2, 5, 8, 12, 16, 23, 38, 56], 23));   // 5

Java

import java.util.*;

public class Main {
    // Returns the index of target in a sorted array, or -1 if it is not there.
    static int binarySearch(int[] sorted, int target) {
        int low = 0;
        int high = sorted.length - 1;

        while (low <= high) {
            int mid = low + (high - low) / 2;          // look at the middle (this form never overflows)
            if (sorted[mid] == target) return mid;
            if (sorted[mid] < target) low = mid + 1;   // discard the left half
            else high = mid - 1;                       // discard the right half
        }
        return -1;                                     // not found
    }

    public static void main(String[] args) {
        int[] data = {2, 5, 8, 12, 16, 23, 38, 56};
        System.out.println(binarySearch(data, 23));    // 5
        System.out.println(binarySearch(data, 7));     // -1
    }
}

Go

package main

import "fmt"

// binarySearch returns the index of target in a sorted slice, or -1 if it is not there.
func binarySearch(sorted []int, target int) int {
	low, high := 0, len(sorted)-1

	for low <= high {
		mid := low + (high-low)/2 // look at the middle
		if sorted[mid] == target {
			return mid
		}
		if sorted[mid] < target {
			low = mid + 1 // discard the left half
		} else {
			high = mid - 1 // discard the right half
		}
	}
	return -1 // not found
}

func main() {
	data := []int{2, 5, 8, 12, 16, 23, 38, 56}
	fmt.Println(binarySearch(data, 23)) // 5
	fmt.Println(binarySearch(data, 7))  // -1
}

Time: O(log n) · Extra space: O(1). 1 million items need at most ~20 checks. 1 billion needs ~30.

Watch out for

  • Running it on unsorted data. You will get confident, wrong answers.
  • Infinite loops from low = mid instead of mid + 1. Always step past the middle you already checked.

Quick check

  1. What must be true before using binary search?
    • Items are sorted
    • Items are unique numbers only
    • The list is short
  2. Roughly how many guesses for 1,000 numbers?
    • 10
    • 500
    • 1,000
  3. The middle item is smaller than the target. Next you…
    • Search the left half
    • Search the right half
    • Start over