Binary Search in C#: Built-in Methods and a Generic Implementation

Binary search finds a value in a sorted array by repeatedly halving the range it looks at. Compare the target with the middle element; if the target is smaller, continue in the left half, otherwise in the right half. Each step discards half of the remaining elements, so a million sorted items need at most 20 comparisons.

The one requirement is in that first sentence: the data must be sorted, using the same ordering you search with. On unsorted data binary search does not fail loudly, it just returns wrong answers.

Use the built-in method

.NET has binary search for arrays, lists and spans:

int[] numbers = [1, 2, 4, 11, 20, 28, 48, 84, 96, 106];

int index = Array.BinarySearch(numbers, 20);
Console.WriteLine(index);     // 4

int missing = Array.BinarySearch(numbers, 30);
Console.WriteLine(missing);   // -7
Console.WriteLine(~missing);  // 6

List<T>.BinarySearch and, for spans, numbers.AsSpan().BinarySearch(20) behave the same way.

The negative result is the useful part. When the value is not found, the method returns the bitwise complement (~) of the index where the value would have to be inserted to keep the array sorted. 30 belongs between 28 and 48, at index 6, so the method returns ~6, which is -7. A sorted list can use that directly:

List<int> sorted = [1, 2, 4, 11, 20];

int i = sorted.BinarySearch(7);
if (i < 0)
    sorted.Insert(~i, 7);   // 1, 2, 4, 7, 11, 20

Test for < 0, not == -1. Any negative number means “not found”.

A generic implementation

Writing it yourself is a classic exercise, and the details are where bugs hide. This version follows the same contract as Array.BinarySearch:

public static class Search
{
    public static int BinarySearch<T>(T[] items, T value) where T : IComparable<T>
        => BinarySearch((ReadOnlySpan<T>)items, value);

    public static int BinarySearch<T>(ReadOnlySpan<T> items, T value) where T : IComparable<T>
    {
        int left = 0;
        int right = items.Length - 1;

        while (left <= right)
        {
            // Not (left + right) / 2: that sum can overflow on very large arrays.
            int middle = left + (right - left) / 2;
            int c = items[middle].CompareTo(value);

            if (c == 0) return middle;
            if (c < 0) left = middle + 1;
            else right = middle - 1;
        }

        // Not found: left is the insertion point.
        return ~left;
    }
}

Usage is the same as the built-in method:

int[] numbers = [1, 2, 4, 11, 20, 28, 48, 84, 96, 106];

Console.WriteLine(Search.BinarySearch(numbers, 20));  // 4
Console.WriteLine(Search.BinarySearch(numbers, 30));  // -7

The details that matter

Midpoint overflow. (left + right) / 2 is the textbook formula and it is wrong for arrays with more than about a billion elements, because the sum exceeds int.MaxValue and turns negative. left + (right - left) / 2 gives the same result without the overflow. The same bug went unnoticed in Java’s Arrays.binarySearch for about nine years.

Loop bounds. With right = Length - 1 the loop condition must be left <= right, and the updates must be middle + 1 and middle - 1. Mixing conventions (for example right = Length with <=) either reads past the end or loops forever.

Duplicates. If the value appears more than once, binary search returns the index of one of them, not necessarily the first. To find the first occurrence, keep searching left after a match instead of returning.

Sort order. If you sorted with a custom comparer, search with the same one: Array.BinarySearch(array, value, comparer). Strings sorted with StringComparer.Ordinal and searched with the culture-sensitive default comparer can give wrong results.

Recursive version

Binary search is often shown recursively. It reads well, but the iterative version above is just as clear and does not use stack space. If you want the recursive form, add this method to the Search class:

public static int BinarySearchRecursive<T>(ReadOnlySpan<T> items, T value, int left, int right)
    where T : IComparable<T>
{
    if (left > right) return ~left;

    int middle = left + (right - left) / 2;
    int c = items[middle].CompareTo(value);

    if (c == 0) return middle;
    return c < 0
        ? BinarySearchRecursive(items, value, middle + 1, right)
        : BinarySearchRecursive(items, value, left, middle - 1);
}

Call it with Search.BinarySearchRecursive<int>(numbers, 20, 0, numbers.Length - 1). The explicit <int> is needed because the compiler does not infer T through the array-to-span conversion on older C# versions. Recursion depth is only about logâ‚‚ n, so stack overflow is not a concern here.

Complexity

CaseTimeExtra space
BestO(1)O(1)
Average and worstO(log n)O(1), or O(log n) recursive

The older version of this post called arr.ToList().BinarySearch(20). That copies the whole array into a new list first, which is O(n) and defeats the point. Call Array.BinarySearch on the array directly.

If your data is not sorted and you search it only once, sorting first costs O(n log n), more than a sequential search. Binary search pays off when you sort once and search many times. If you mostly look values up by key, a HashSet<T> or Dictionary<TKey, TValue> gives O(1) lookups without sorting at all.

Related examples

1 thought on “Binary Search in C#: Built-in Methods and a Generic Implementation”

Leave a Comment