M12 · Searching

Binary Search: Halving a Sorted Range

A sorted array lets you rule out half of the remaining elements with a single comparison. Binary search repeats that until one candidate is left or none are. This lesson walks through every pointer move, proves the loop is correct, and shows how to get the first of several equal values.

~35 minBeginnerC# · Python · Java · C++
Curriculum: M12 Searching · 3 of 3 lessons available

You will be able to

  • Trace low, mid and high through a binary search and say which elements each comparison rules out.
  • State the loop invariant and use it to explain why the search is correct and always terminates.
  • Derive the ⌊log₂ n⌋ + 1 bound on iterations and compare it with a linear scan.
  • Choose between "any match" and "first occurrence" (lower bound), and write both without off-by-one errors.
  • Use the built-in binary searches of C#, Python, Java and C++ and read their not-found results correctly.

Helpful before this lesson

  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.
  • M05 Arrays — Contiguous storage, index arithmetic, and how a dynamic array grows while keeping append cheap.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

Looking for a word in a printed dictionary, you do not start at page one. You open it near the middle, see whether your word comes before or after that page, and throw away the half that cannot contain it. Binary search is exactly that, done on an array that is sorted in ascending order.

It keeps a range of candidates, the only positions where the target can still be:

  • low: the first candidate.
  • high: the last candidate (classic version) or one past it (first-occurrence version).
  • mid: the middle of the range, the one element looked at in this iteration.

Comparing values[mid] with the target settles the fate of every element on one side at once. If values[mid] < target, then because the array is sorted, everything at or left of mid is smaller too, so low jumps to mid + 1. Otherwise high moves left. The lab fades every element that has been ruled out, so you can watch the range collapse.

Sorted order is not a detail; it is the whole reason the method works. On unsorted input binary search does not fail loudly, it silently returns wrong answers. That is why the lab rejects unsorted input instead of sorting it behind your back.

The classic version

low = 0, high = n - 1
while low <= high:
    mid = low + (high - low) / 2
    if values[mid] == target: return mid
    if values[mid] < target:  low = mid + 1
    else:                     high = mid - 1
return -1

Loop invariant. If the target is anywhere in the array, it is at an index in [low, high]. It holds at the start (the range is the whole array) and each update keeps it, because it only discards positions whose values are known to be too small or too large. When low > high the range is empty, so the target is not present and returning -1 is correct.

Termination. Each iteration either returns or makes the range strictly smaller: low grows past mid or high drops below it. A range of n elements cannot shrink forever.

Why low + (high - low) / 2

(low + high) / 2 is mathematically the same, but in C#, Java and C++ the sum can exceed the largest int when the array is huge, wrap around to a negative number and index outside the array. This exact bug sat in the JDK's own Arrays.binarySearch for about nine years before it was found in 2006. low + (high - low) / 2 never exceeds high. Python integers have arbitrary precision, so the Python version keeps the simpler (low + high) // 2.

The C++ code uses std::ptrdiff_t (signed) indices on purpose: with high = size - 1, an empty span needs high = -1, which an unsigned std::size_t would turn into a huge positive number.

Why it is logarithmic

Each iteration leaves at most half of the candidates: a range of r elements becomes at most ⌊r / 2⌋. Starting from n, after k iterations at most n / 2ᵏ candidates remain, and the loop cannot run once that drops below one. So the number of iterations is at most

⌊log₂ n⌋ + 1

which is 4 for 10 elements, 7 for 64, 20 for a million and 31 for two billion. A linear scan needs up to n comparisons. The chart in the lab draws the range size before each iteration next to that bound; the 64 values, worst case preset hits it exactly.

Time Extra space
Best case (target at the first mid) O(1) O(1)
Worst and average case O(log n) O(1)
Recursive version O(log n) O(log n) call stack

The classic version evaluates up to two comparisons per iteration (==, then <), which the Comparisons metric counts separately. The first-occurrence version does one per iteration plus one at the end, so it often compares less even though it never stops early.

O(log n) assumes reaching values[mid] costs O(1), which is true for arrays. On a linked list the comparisons are still logarithmic, but walking to the middle is linear, so the whole search is O(n).

Duplicates: any match or the first one

With duplicates the classic version returns some index of the target, whichever one a mid lands on first. In [1, 3, 3, 3, 3, 3, 7, 9] it returns 3, not 1. That is a legitimate contract (the built-ins below promise no more), but often you need the first or last copy, or the position where a missing value would go.

The lower bound is the first index whose value is ≥ target. It uses a half-open range [low, high) and never stops early:

low = 0, high = n
while low < high:
    mid = low + (high - low) / 2
    if values[mid] < target: low = mid + 1
    else:                    high = mid      # mid may be the answer; keep it
return low

The invariant is now: everything left of low is smaller than the target, and everything at or right of high is ≥ the target. When low == high, that index is the lower bound. It may be n (every value is smaller). The first occurrence is the lower bound if values[low] == target, otherwise the target is absent. Compare the presets Duplicates: any match and Duplicates: first match in the lab: same array, different contract, different result.

Two details make the half-open version safe. high = mid, not mid - 1, because mid itself may be the answer. And mid is always strictly below high, so it is always a real index and the range always shrinks.

Language Call Not found Duplicates
C# Array.BinarySearch(a, x), List<T>.BinarySearch(x) negative number: the bitwise complement ~i of the index of the next larger element any matching index
Python bisect.bisect_left(a, x) / bisect_right no "found" result: returns the insertion point; check a[i] == x yourself bisect_left gives the first position
Java Arrays.binarySearch(a, x), Collections.binarySearch(list, x) -(insertion point) - 1 "no guarantee which one will be found"
C++ std::binary_search (bool), std::lower_bound, std::upper_bound, std::equal_range lower_bound returns the insertion position lower_bound gives the first

All of them assume sorted input and say the result is undefined (or unspecified) otherwise; none of them checks. Python's bisect functions accept a key= function since Python 3.10. Java's Collections.binarySearch on a large list without random access (such as LinkedList) walks the list with an iterator: O(log n) comparisons but O(n) traversal, the caveat from the previous section. C++ lower_bound likewise needs only forward iterators, and is linear in steps on them.

The teaching implementation

IndexOf / index_of is the classic version and FirstIndexOf / first_index_of the lower-bound version, written the same way in all four languages so the lab can highlight the matching lines in each. The listings below are the exact files the tests run: every language reads one shared fixture file (found, missing, empty, single element, duplicates, extremes), where the classic result for duplicates is a range of acceptable indices rather than one exact index. Each language also compares its results with its built-in search on 2,000 random sorted arrays.

Common mistakes

  • Searching unsorted data. The result is meaningless, not an error. Sort first (O(n log n)) or use a hash set if you only need membership.
  • Mixing interval conventions. while (low <= high) belongs with high = n - 1 and high = mid - 1; while (low < high) with high = n and high = mid. Mixing them either skips the last candidate or loops forever on a two-element range.
  • low = mid instead of mid + 1. When high = low + 1, mid == low, so the range never shrinks and the loop never ends.
  • Overflowing the midpoint in fixed-width integer languages.
  • Treating the built-in's negative result as an index. In C# and Java it encodes the insertion point; decode it with ~i or -(i + 1).

Edge cases

  • Empty array: the loop never runs; the result is -1 without any comparison.
  • One element: one iteration.
  • Target smaller than every element: high keeps moving left until it is -1 (classic); the lower bound is 0.
  • Target larger than every element: low ends at n; the lower bound is n, one past the end.
  • All elements equal to the target: the classic version returns the middle one; the first-occurrence version returns 0.

Worked practice

1. How many iterations does the classic search take at most on 1,000 elements?

Answer

⌊log₂ 1000⌋ + 1 = 9 + 1 = 10 (2⁹ = 512 ≤ 1000 < 1024 = 2¹⁰).

2. In [2, 4, 4, 4, 9], what do the classic and first-occurrence versions return for 4?

Answer

Classic: the first mid is 2, and values[2] = 4, so it returns 2. First occurrence: the lower bound is 1, and values[1] = 4, so it returns 1.

3. How do you find the last occurrence of a value?

Answer

Find the upper bound, the first index whose value is > target (change < to <= in the lower-bound loop), then check the element just before it: if upper > 0 and values[upper - 1] == target, the last occurrence is upper - 1. The number of copies is upper - lower.

4. Why can the first-occurrence loop not stop as soon as it sees the target?

Answer

A match at mid proves only that the first occurrence is at mid or earlier. Elements left of mid may also equal the target, so it keeps mid in the range (high = mid) and continues until the range is empty.

Summary

  • Binary search needs sorted input and random access; it rules out half the candidates per step.
  • At most ⌊log₂ n⌋ + 1 iterations: O(log n) time, O(1) extra space iteratively.
  • The loop invariant ("if present, the target is in the range") proves correctness.
  • With duplicates, decide what you need: any match, the first (lower bound) or the last (upper bound).
  • Built-ins encode "not found" differently: C# ~i, Java -(i + 1), Python and C++ return the insertion point directly.

Full implementation

Both searches in four languages, each checked against one shared set of test cases (found, missing, empty, one element, duplicates, extremes) and 2,000 random sorted arrays compared with the language's built-in binary search.

namespace Bekadan.Dsa.Examples.Searching;
 
/// <summary>
/// Binary search over an array sorted in ascending order.
/// Both methods run in O(log n) time and O(1) extra space; neither checks
/// that the input is sorted (that check alone would cost O(n)).
/// </summary>
public static class BinarySearch
{
    /// <summary>
    /// Returns the index of an element equal to <paramref name="target"/>, or -1.
    /// With duplicates, which matching index is returned is unspecified,
    /// the same contract as <see cref="Array.BinarySearch(Array, object)"/>.
    /// </summary>
    public static int IndexOf(ReadOnlySpan<int> values, int target)
    {
        int low = 0, high = values.Length - 1;
        while (low <= high)
        {
            int mid = low + (high - low) / 2; // (low + high) / 2 could overflow int
            if (values[mid] == target)
                return mid;
            if (values[mid] < target)
                low = mid + 1;
            else
                high = mid - 1;
        }
        return -1;
    }
 
    /// <summary>
    /// Returns the index of the first element equal to <paramref name="target"/>, or -1.
    /// Finds the lower bound (the first index whose value is &gt;= target) in a
    /// half-open range [low, high), then checks that one element.
    /// </summary>
    public static int FirstIndexOf(ReadOnlySpan<int> values, int target)
    {
        int low = 0, high = values.Length;
        while (low < high)
        {
            int mid = low + (high - low) / 2;
            if (values[mid] < target)
                low = mid + 1;
            else
                high = mid; // values[mid] may be the first match: keep it
        }
        if (low < values.Length && values[low] == target)
            return low;
        return -1;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Searching/BinarySearch.cs

"""Binary search over a list sorted in ascending order.
 
Both functions run in O(log n) time and O(1) extra space. Neither checks that
the input is sorted: that check alone would cost O(n).
"""
 
from collections.abc import Sequence
 
 
def index_of(values: Sequence[int], target: int) -> int:
    """Return the index of an element equal to target, or -1.
 
    With duplicates, which matching index is returned is unspecified.
    """
    low, high = 0, len(values) - 1
    while low <= high:
        mid = (low + high) // 2  # Python ints never overflow
        if values[mid] == target:
            return mid
        if values[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1
 
 
def first_index_of(values: Sequence[int], target: int) -> int:
    """Return the index of the first element equal to target, or -1.
 
    Finds the lower bound (the first index whose value is >= target, which is
    what bisect.bisect_left returns) in a half-open range [low, high), then
    checks that one element.
    """
    low, high = 0, len(values)
    while low < high:
        mid = (low + high) // 2
        if values[mid] < target:
            low = mid + 1
        else:
            high = mid  # values[mid] may be the first match: keep it
    if low < len(values) and values[low] == target:
        return low
    return -1

Tested on CPython 3.14.0 · examples/python/dsa_examples/binary_search.py

package dev.bekadan.dsa.searching;
 
/**
 * Binary search over an array sorted in ascending order. Both methods run in
 * O(log n) time and O(1) extra space; neither checks that the input is sorted
 * (that check alone would cost O(n)).
 */
public final class BinarySearch {
    private BinarySearch() {
    }
 
    /**
     * Returns the index of an element equal to {@code target}, or -1. With
     * duplicates, which matching index is returned is unspecified, the same
     * contract as {@link java.util.Arrays#binarySearch(int[], int)}.
     */
    public static int indexOf(int[] values, int target) {
        int low = 0, high = values.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2; // (low + high) / 2 could overflow int
            if (values[mid] == target) {
                return mid;
            }
            if (values[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }
 
    /**
     * Returns the index of the first element equal to {@code target}, or -1.
     * Finds the lower bound (the first index whose value is &gt;= target) in a
     * half-open range [low, high), then checks that one element.
     */
    public static int firstIndexOf(int[] values, int target) {
        int low = 0, high = values.length;
        while (low < high) {
            int mid = low + (high - low) / 2;
            if (values[mid] < target) {
                low = mid + 1;
            } else {
                high = mid; // values[mid] may be the first match: keep it
            }
        }
        if (low < values.length && values[low] == target) {
            return low;
        }
        return -1;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/searching/BinarySearch.java

#pragma once
 
#include <cstddef>
#include <span>
 
namespace bekadan::dsa {
 
// Binary search over a span sorted in ascending order. Both functions run in
// O(log n) time and O(1) extra space; neither checks that the input is sorted
// (that check alone would cost O(n)).
 
// Returns the index of an element equal to target, or -1. With duplicates,
// which matching index is returned is unspecified.
// Signed indices: with high = size - 1, an empty span must give high = -1.
inline std::ptrdiff_t index_of(std::span<const int> values, int target) {
    std::ptrdiff_t low = 0, high = std::ssize(values) - 1;
    while (low <= high) {
        std::ptrdiff_t mid = low + (high - low) / 2;  // (low + high) / 2 could overflow
        if (values[mid] == target) {
            return mid;
        }
        if (values[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return -1;
}
 
// Returns the index of the first element equal to target, or -1. Finds the
// lower bound (what std::lower_bound returns) in a half-open range
// [low, high), then checks that one element.
inline std::ptrdiff_t first_index_of(std::span<const int> values, int target) {
    std::ptrdiff_t low = 0, high = std::ssize(values);
    while (low < high) {
        std::ptrdiff_t mid = low + (high - low) / 2;
        if (values[mid] < target) {
            low = mid + 1;
        } else {
            high = mid;  // values[mid] may be the first match: keep it
        }
    }
    if (low < std::ssize(values) && values[low] == target) {
        return low;
    }
    return -1;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/binary_search.hpp

References