Searching · O(log n)

Binary search

low, mid and high on a sorted array; any match or first occurrence.

The full explanation, derivation and practice are in the lesson Binary search: halving a sorted range.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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