In C#, Array.BinarySearch looks for a value inside a sorted array. It uses the binary search algorithm, which is fast on large arrays because it jumps to the middle instead of scanning one by one.
If the value exists, you get its index. If it is missing, you get a negative number. Use ~result (bitwise complement) to learn where the value would be inserted to keep the array sorted.
This is a static member of System.Array. You call it with the class name, such as Array.BinarySearch(...). Arrays in C# have a fixed length after creation; use List<T> when the count must grow.
Syntax
Sort first (unless the array is already ordered), then call Array.BinarySearch.
C#
Array.Sort(nums);
int ix = Array.BinarySearch(nums, 30);
Call
What it does
Array.BinarySearch(nums, 30)
Searches the whole sorted array for 30.
Array.BinarySearch(nums, 1, 3, 20)
Searches a range: index 1, length 3.
Results are undefined if the array is not sorted according to the comparer you use.
Library declarations
C#
public static int BinarySearch(Array array, object value);
public static int BinarySearch<T>(T[] array, T value);
Parameters
Parameter
Description
array
Required. Must be sorted.
value
Required. The value to find.
Return Value
Return Value
Description
index (>= 0)
The value was found at that index (if duplicates exist, any matching index may be returned).
negative
Not found. ~result is the insertion point.
C# Examples
Example 1 — Find a Value After Sort
Sort numbers, then binary-search for 30.
C#
using System;
class Program {
static void Main() {
int[] nums = { 40, 10, 30, 20 };
Array.Sort(nums);
int ix = Array.BinarySearch(nums, 30);
Console.WriteLine("Sorted: " + string.Join(", ", nums));
Console.WriteLine("Index of 30: " + ix);
}
}