Algorithm · Searching · O(log n)
Binary search
Halve a sorted range with every comparison: O(log n) to find a value or the first position where it could go.
The full derivation, edge cases and exercises are in the lesson Counting operations and growth rates: O, Θ and Ω. Open it full width in the playground.
On this page
The idea
On a sorted array, one comparison with the middle element rules out half of the remaining range. Repeating that leaves one candidate after about log₂ n steps.
Most bugs are boundary bugs. Fix one convention (here a half-open or closed range, stated in the lesson) and keep the invariant in mind, and the “first occurrence” variant (lower bound) follows naturally.
Steps
- Keep a range [low, high] that must contain the target if it exists.
- Compare the target with the middle element.
- Discard the half that cannot contain it.
- Stop when the element is found or the range is empty.
Invariants
What holds at every step; the correctness argument rests on these.
- If the target is in the array, it lies inside the current range.
- The range shrinks on every iteration, so the loop terminates.
Complexity
| Case | Time | Extra space | Notes |
|---|---|---|---|
| Search | O(log n) | O(1) iterative | At most ⌊log₂ n⌋ + 1 iterations. |
| Lower bound (first occurrence) | O(log n) | O(1) |
When to use it
Use it when
- The data is sorted (or a predicate over it is monotonic) and you search it more than once.
- You need the insertion point, the first or last occurrence, or a count of values in a range.
Avoid it when
- The data is unsorted and searched once: sorting costs more than a linear scan.
- The structure has no random access (a linked list): reaching the middle is already O(n).
Step through it
The interactive lab for binary search: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.
Implementation in four languages
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 >= 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 >= 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
Learn more
Lessons
- Counting operations and growth rates: O, Θ and Ω· M03 Big O
- Binary search: halving a sorted range· M12 Searching
Data structures it uses
Comparisons
- Linear search vs binary search· A left-to-right scan against halving the range, on one sorted array. The scan wins only when the target sits near the front.
Problems, patterns and exercises
- ProblemWhere does a value start and end?· intermediate · O(log n)
- PatternBinary search on a monotonic predicate· O(log R × cost of ok)
- Complexity exerciseHalving until one is left· Θ(log n)