AlgoTales · Roadmap

Binary search

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

Where you will meet this in real life

Binary search finds something in sorted data by checking the middle and discarding the half that cannot contain it, repeated until found. Even for a million items it needs only about twenty looks, and the same idea finds the point where a yes-or-no answer flips.

Practical use cases

  • Web app: Finding the bad release with git bisect. A site broke somewhere in the last 200 commits. Testing the middle one tells you whether the bug is earlier or later. About 8 tests find the exact commit, where checking each one would take up to 200.
  • Web app: Autocomplete or phonebook lookup. A contact list kept in alphabetical order is searched as the user types. Jumping to the middle and halving finds the first matching name quickly, so suggestions appear without delay. The suggestions appear as the user types, because each keystroke needs only about 20 checks.
  • Web app: Price filter on a sorted product list. A shop page shows products sorted by price, and the user sets "under 500 rupees". Binary search finds the cut-off position immediately, so the filter responds at once even for a catalogue with a million products.
  • System: Database indexes and rotated data. Database indexes are built on the same halving idea. It even works on sorted data that has been rotated, like a ring buffer, with a small tweak, which is why databases, git and ring-buffer code all lean on it.

The story: The Library Shelf That Was Rotated

The school library had one long shelf of books in number order: 0, 1, 2, 4, 5, 6, 7. During Diwali cleaning, a helper picked up the last part of the shelf and put it at the front by mistake. Now the shelf read 4, 5, 6, 7, 0, 1, 2. "It is still nearly in order," said Mrs. Sharma. "Find book 0 without reading every book."

Kabir groaned: "It is not sorted any more, so I must scan." Mira pointed at the clue: "sorted" and "find" and "faster than reading all". Those words smell of binary search. "Open the middle book. Cut the shelf there. One of the two halves is always perfectly sorted. Check whether the target fits inside that sorted half. If yes, keep it. If not, throw it away and keep the other half."

Each peek removes half the shelf, even though the shelf is bent. Within three peeks Kabir held book 0.

The lesson: binary search is not only for plain sorted lists. Whenever you can look at one middle spot and safely throw away half of what remains, binary search applies.

How to spot this problem, and where you need it

You have a lot of ordered data, or a yes/no check that flips from no to yes at some point, and you are scanning from the beginning each time.

Signs you need it

  • The list is sorted and you use a loop, array_search() or in_array() to find a value or a boundary.
  • The wording says "sorted", "first value that is at least", "find the position to insert", or "first failing version".
  • Doubling the data makes search noticeably slower, but each check gives you a clear "too high" or "too low".

Where to use it in a project

  • Looking up ids, dates or prices in a sorted list you already hold in memory.
  • Finding the first bad build, first failing deployment or first date that has data.
  • Finding the insert position and range boundaries in sorted results.

The solution

Keep two markers for the part of the list that could still hold the answer. Look at the middle item. If it is too small, throw away the left half; if too big, throw away the right half; if it is a match, stop. Repeat on what is left. For a yes/no flip, test the middle and keep the half where the flip must be.

Payoff: Before: up to a million checks per search. After: about 20, so lookups feel instant.

Explain it like I am 8

You are guessing a number between 1 and 100 and your friend says higher or lower. You always guess the middle, so each answer cuts the choices in half. Binary search is that game on a list, and your friend is the sorted order.

How it works, step by step

  1. Clues: "sorted", "find in log time", "rotated", "first/last position", "can you do better than O(n)?" Think binary search.
  2. Keep a search zone [lo .. hi] and look at the middle: mid = (lo + hi) / 2.
  3. If mid is the target, you are done.
  4. Find which half is sorted: if a[lo] <= a[mid], the left half is sorted; otherwise the right half is.
  5. Does the target fit inside the sorted half? If yes keep that half, otherwise keep the other. Repeat until the zone is empty (answer: not found).

The code in four languages

PHP

<?php
// Search in a rotated sorted array. Returns the index or -1.
function searchRotated(array $a, int $target): int {
    $lo = 0;
    $hi = count($a) - 1;
    while ($lo <= $hi) {
        $mid = intdiv($lo + $hi, 2);
        if ($a[$mid] === $target) {
            return $mid;
        }
        if ($a[$lo] <= $a[$mid]) {                       // left half is sorted
            if ($a[$lo] <= $target && $target < $a[$mid]) {
                $hi = $mid - 1;                          // target is inside it
            } else {
                $lo = $mid + 1;
            }
        } else {                                         // right half is sorted
            if ($a[$mid] < $target && $target <= $a[$hi]) {
                $lo = $mid + 1;                          // target is inside it
            } else {
                $hi = $mid - 1;
            }
        }
    }
    return -1;
}
echo searchRotated([4, 5, 6, 7, 0, 1, 2], 0), "\n";      // 4
echo searchRotated([4, 5, 6, 7, 0, 1, 2], 3);            // -1

JavaScript

// Search in a rotated sorted array. Returns the index or -1.
function searchRotated(a, target) {
  let lo = 0;
  let hi = a.length - 1;
  while (lo <= hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (a[mid] === target) {
      return mid;
    }
    if (a[lo] <= a[mid]) {                        // left half is sorted
      if (a[lo] <= target && target < a[mid]) {
        hi = mid - 1;                             // target is inside it
      } else {
        lo = mid + 1;
      }
    } else {                                      // right half is sorted
      if (a[mid] < target && target <= a[hi]) {
        lo = mid + 1;                             // target is inside it
      } else {
        hi = mid - 1;
      }
    }
  }
  return -1;
}
console.log(searchRotated([4, 5, 6, 7, 0, 1, 2], 0));   // 4
console.log(searchRotated([4, 5, 6, 7, 0, 1, 2], 3));   // -1

Java

public class Main {
    // Search in a rotated sorted array. Returns the index or -1.
    static int searchRotated(int[] a, int target) {
        int lo = 0;
        int hi = a.length - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (a[mid] == target) {
                return mid;
            }
            if (a[lo] <= a[mid]) {                         // left half is sorted
                if (a[lo] <= target && target < a[mid]) {
                    hi = mid - 1;                          // target is inside it
                } else {
                    lo = mid + 1;
                }
            } else {                                       // right half is sorted
                if (a[mid] < target && target <= a[hi]) {
                    lo = mid + 1;                          // target is inside it
                } else {
                    hi = mid - 1;
                }
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(searchRotated(new int[]{4, 5, 6, 7, 0, 1, 2}, 0));   // 4
        System.out.println(searchRotated(new int[]{4, 5, 6, 7, 0, 1, 2}, 3));   // -1
    }
}

Go

package main

import "fmt"

// searchRotated searches a rotated sorted slice. Returns the index or -1.
func searchRotated(a []int, target int) int {
	lo, hi := 0, len(a)-1
	for lo <= hi {
		mid := lo + (hi-lo)/2
		if a[mid] == target {
			return mid
		}
		if a[lo] <= a[mid] { // left half is sorted
			if a[lo] <= target && target < a[mid] {
				hi = mid - 1 // target is inside it
			} else {
				lo = mid + 1
			}
		} else { // right half is sorted
			if a[mid] < target && target <= a[hi] {
				lo = mid + 1 // target is inside it
			} else {
				hi = mid - 1
			}
		}
	}
	return -1
}

func main() {
	fmt.Println(searchRotated([]int{4, 5, 6, 7, 0, 1, 2}, 0)) // 4
	fmt.Println(searchRotated([]int{4, 5, 6, 7, 0, 1, 2}, 3)) // -1
}

Time: O(log n) · Extra space: O(1). Each peek throws away half the shelf, so a million books need only about twenty peeks.

Watch out for

  • Using a[lo] < a[mid] instead of <=. When the zone has one or two items, lo and mid can be the same place.
  • Computing the target-in-half test with the wrong end (forgetting that the middle itself was already checked).
  • Using binary search on data that has duplicates all over the rotation point without extra care; it can degrade.

Quick check

  1. In a rotated sorted array, what is always true after cutting at the middle?
    • Both halves are sorted
    • Neither half is sorted
    • At least one half is sorted
  2. Which clue says "binary search"?
    • "Sorted" with a request for better than linear time
    • "Longest repeating substring"
    • "Connect all computers cheaply"
  3. How many peeks for about 1,000 books?
    • About 500
    • About 100
    • About 10