In C#, List.BinarySearch(item) finds a value in a sorted list by jumping to the middle, then to the middle of the half that could hold the value, and so on. A list of one million items needs only about 20 steps, while IndexOf() may need a million.
If the value is found you get its index. If not, you get a negative number. Apply the bitwise complement ~result to that number to get the index where the value would have to be inserted to keep the list sorted. The list must already be in the order that the comparer expects, or the answer is meaningless.
This is an instance member of List<T> (System.Collections.Generic). Call it on a list variable, such as numbers.BinarySearch(...). A List<T> is a class, so two variables can share one list. It keeps items in the order you put them, allows duplicates, and grows when needed. An array, by comparison, has a fixed length.
Syntax
Sort the list first (unless it is already sorted), then search. Pass a comparer when the list is not in the default order.
C#
List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };
int found = numbers.BinarySearch(40); // 3
int miss = numbers.BinarySearch(35); // negative
int insertAt = ~miss; // 3
Call
What it does
numbers.BinarySearch(40)
Searches the whole list with the default comparer.
numbers.BinarySearch(40, comparer)
Uses your own IComparer<T>, such as one for descending order.
numbers.BinarySearch(1, 3, 40, null)
Searches only 3 items from index 1. null means the default comparer.
The list must be sorted with the same comparer you search with. If the list holds duplicates, the method may return any one of the matching indexes, not necessarily the first. Compare this with Array.BinarySearch, which does the same job as a static method on arrays.
Library declarations
C#
public int BinarySearch(T item);
public int BinarySearch(T item, IComparer<T> comparer);
public int BinarySearch(int index, int count, T item, IComparer<T> comparer);
Parameters
Parameter
Description
item
Required. The value to look for.
comparer
Optional overload. An IComparer<T> that defines the order. null uses the default order of T.
index, count
Optional overload. Search only count items starting at index.
Return Value
Return Value
Description
int (0 or more)
The index where the item was found.
negative
Not found. ~result is the index of the first item larger than the value, or Count if there is none. That is the insertion point.
C# Examples
Example 1 — Search a Sorted List
The numbers are already in ascending order, so binary search can find them.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };
Console.WriteLine(numbers.BinarySearch(40));
Console.WriteLine(numbers.BinarySearch(10));
Console.WriteLine(numbers.BinarySearch(35));
}
}
Output
3
0
-4
How It Works
Middle first. For 40 the search compares with the middle item 30, sees that 40 is larger, and continues in the right half.
Found. It reaches index 3, where 40 sits, and returns 3. A non-negative result always means a hit.
First item works too.10 is at index 0, so the result is 0.
Not found is negative.35 would belong at index 3, between 30 and 40. The method returns the complement of 3, which is -4.
Example 2 — Decode the Negative Result
When a value is missing, ~result tells you where it would go. Try the front, the middle, and the end.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
List<int> list = new List<int> { 2, 4, 8, 16 };
int[] probes = { 5, 100, 1 };
foreach (int p in probes) {
int r = list.BinarySearch(p);
Console.WriteLine(p + ": raw " + r + ", insert at " + ~r);
}
}
}
Output
5: raw -3, insert at 2
100: raw -5, insert at 4
1: raw -1, insert at 0
How It Works
Middle.5 sits between 4 and 8. The raw result is -3, and ~(-3) is 2, the index of 8.
Past the end.100 is bigger than everything, so the insertion point is 4, which equals Count. The raw result is -5.
Before the start.1 is smaller than everything, so the insertion point is 0 and the raw result is -1.
Why a complement. Index 0 is a valid hit, so the "not found" signal must be less than 0. Using ~index keeps both facts in one number.
Example 3 — BinarySearch with a Comparer
The list is sorted from big to small. Pass a comparer that uses the same order, or the search goes the wrong way.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
List<int> desc = new List<int> { 50, 40, 30, 20, 10 };
Comparer<int> backwards = Comparer<int>.Create((x, y) => y.CompareTo(x));
Console.WriteLine(desc.BinarySearch(30, backwards));
int r = desc.BinarySearch(35, backwards);
Console.WriteLine(r);
Console.WriteLine(~r);
}
}
Output
2
-3
2
How It Works
Same order for both. The list runs 50 down to 10. The comparer y.CompareTo(x) reverses the normal order, so it agrees with the list.
Found.30 is in the middle at index 2, so the result is 2.
Missing 35. In descending order, 35 belongs between 40 and 30. That is index 2, so the raw result is -3.
Complement again.~r gives 2, the index where an Insert would keep the list in descending order.
Frequently Asked Questions
Yes. The list must be sorted in the order the comparer expects. On an unsorted list the result is unreliable.
The value was not found. Use ~result to get the index where the value could be inserted to keep the list sorted.
On large sorted lists, yes: it takes about log2(n) steps instead of n. On small lists the difference is tiny.
BinarySearch may return the index of any one of the matching items, not always the first or last.
They work the same way. List.BinarySearch is an instance method (numbers.BinarySearch(x)). Array.BinarySearch is a static method (Array.BinarySearch(arr, x)).