How to use Array.BinarySearch() Method in C# | Set -2
Last Updated :
11 Jul, 2025
Array.BinarySearch() method is used to search a value in a sorted
one dimensional array. The
binary search algorithm is used by this method. This algorithm searches a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.
There are total 8 methods in the overload list of this method as follows:
- BinarySearch(Array, Object) Method
- BinarySearch(Array, Object, IComparer) Method
- BinarySearch(Array, Int32, Int32, Object) Method
- BinarySearch(Array, Int32, Int32, Object, IComparer) Method
- BinarySearch<T>(T[], T) Method
- BinarySearch<T>(T[], T, IComparer<T>) Method
- BinarySearch<T>(T[], Int32, Int32, T) Method
- BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>) Method
Here, the first 4 methods are already discussed in
Set-1. Last 4 methods will be discussed in this set
BinarySearch<T>(T[], T) Method
This method searches for a specific element in a sorted one-dimensional array. It will search the entire array. The search uses an
IComparable<T> generic interface which is implemented by each element of the array or by a specific object.
Syntax: public static int BinarySearch<T>(T[] arr, T val);
Here, "T" is the type of the elements of the array.
Parameters:
arr: It is the one-dimensional sorted array to search for.
val: It is the object to search for.
Return Value: It returns the index of the specified
valin the specified
arr if the
val is found otherwise it returns a negative number. There are different cases of return values as follows:
- If the val is not found and valis less than one or more elements in the arr, the negative number returned is the bitwise complement of the index of the first element that is larger than val.
- If the val is not found and val is greater than all elements in the arr, the negative number returned is the bitwise complement of (the index of the last element plus 1).
- If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if the val is present in the arr.
Exceptions:
- ArgumentNullException: If the arr is null.
- InvalidOperationException: If the T does not implement the IComparable<T> generic interface.
Example 1:
csharp
// C# program to demonstrate the use of
// BinarySearch<T>(T[], T) method
using System;
using System.Collections.Generic;
class GFG {
// Main Method
public static void Main()
{
string[] arr = {"ABC", "XYZ",
"JKL", "DEF", "MNO"};
Console.WriteLine("Original array");
foreach(string g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nAfter Sort");
// sort the array
Array.Sort(arr);
foreach(string g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nBinarySearch for 'GHI':");
// call "BinarySearch<T>(T[], T)" method
int index = Array.BinarySearch(arr, "GHI");
sort(arr, index);
}
// BinarySearch<T> method
private static void sort<T>(T[] array, int index)
{
if (index < 0)
{
// If the index is negative,
// it represents the bitwise
// complement of the next
// larger element in the array.
index = ~index;
Console.Write("Sorts between: ");
if (index == 0)
Console.Write("beginning of array and ");
else
Console.Write("{0} and ", array[index - 1]);
if (index == array.Length)
Console.WriteLine("end of array.");
else
Console.WriteLine("{0}.", array[index]);
}
else
{
Console.WriteLine("Found at index {0}.", index);
}
}
}
Output:
Original array
ABC
XYZ
JKL
DEF
MNO
After Sort
ABC
DEF
JKL
MNO
XYZ
BinarySearch for 'GHI':
Sorts between: DEF and JKL.
Example 2:
csharp
// C# program to demonstrate the use
// of BinarySearch<T>(T[], T) method
using System;
using System.Collections.Generic;
class GFG {
// Main Method
public static void Main()
{
int[] arr = {5, 7, 1, 3, 4, 2};
Console.WriteLine("Original array");
foreach(int g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nAfter Sort");
// sort the array
Array.Sort(arr);
foreach(int g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nBinarySearch for '6':");
// call "BinarySearch<T>(T[], T)" method
int index = Array.BinarySearch(arr, 6);
sort(arr, index);
}
// BinarySearch<T> method
private static void sort<T>(T[] array, int index)
{
if (index < 0)
{
// If the index is negative,
// it represents the bitwise
// complement of the next
// larger element in the array.
index = ~index;
Console.Write("Sorts between: ");
if (index == 0)
Console.Write("beginning of array and ");
else
Console.Write("{0} and ", array[index - 1]);
if (index == array.Length)
Console.WriteLine("end of array.");
else
Console.WriteLine("{0}.", array[index]);
}
else
{
Console.WriteLine("Found at index {0}.", index);
}
}
}
Output:
Original array
5
7
1
3
4
2
After Sort
1
2
3
4
5
7
BinarySearch for '6':
Sorts between: 5 and 7.
BinarySearch<T>(T[], T, IComparer<T>) Method
This method searches for a specific value in a one-dimensional sorted array specified using IComparer<T> generic interface.
Syntax: public static int BinarySearch<T> (T[] arr, T val, IComparer comparer);
Here, "T" is the type of the elements of the array.
Parameters:
arr: It is the one-dimensional sorted array to search for.
val: It is the object to search for.
comparer: It is theIComparer<T> implementation to use when comparing elements.
Return Value: It returns the index of the specified
valin the specified
arr if the
val is found otherwise it returns a negative number. There are different cases of return values as follows:
- If the val is not found and valis less than one or more elements in the arr, the negative number returned is the bitwise complement of the index of the first element that is larger than val.
- If the val is not found and val is greater than all elements in the arr, the negative number returned is the bitwise complement of (the index of the last element plus 1).
- If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if the val is present in the arr.
Exceptions:
- ArgumentNullException: If the array is null.
- InvalidOperationException: If the comparer is null and T does not implement the IComparable<T> generic interface.
- ArgumentException: If the comparer is null, and value is of a type that is not compatible with the elements of array.
Example:
csharp
// C# program to demonstrate the use of
// BinarySearch<T>(T[], T, IComparer<T>)
// method
using System;
using System.Collections.Generic;
class comparer : IComparer<string> {
public int Compare(string x, string y)
{
return x.CompareTo(y);
}
}
// Driver Class
class GFG {
// Main Method
public static void Main()
{
string[] arr = {"ABC", "XYZ",
"JKL", "DEF", "MNO"};
Console.WriteLine("Original Array");
foreach(string g in arr)
{
Console.WriteLine(g);
}
// IComparer<T> object
comparer gg = new comparer();
Console.WriteLine("\nAfter Sort");
// sort the array
Array.Sort(arr, gg);
foreach(string g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nBinarySearch for 'GHI':");
// search for "GHI"
int index = Array.BinarySearch(arr, "GHI", gg);
sort(arr, index);
}
// BinarySearch<T> method
private static void sort<T>(T[] array, int index)
{
if (index < 0) {
// If the index is negative,
// it represents the bitwise
// complement of the next
// larger element in the array.
index = ~index;
Console.Write("Sorts between: ");
if (index == 0)
Console.Write("beginning of array and ");
else
Console.Write("{0} and ", array[index - 1]);
if (index == array.Length)
Console.WriteLine("end of array");
else
Console.WriteLine("{0}", array[index]);
}
else
{
Console.WriteLine("Found at index {0}", index);
}
}
}
Output:
Original Array
ABC
XYZ
JKL
DEF
MNO
After Sort
ABC
DEF
JKL
MNO
XYZ
BinarySearch for 'GHI':
Sorts between: DEF and JKL
BinarySearch<T>(T[], Int32, Int32, T)
This method searches a range of elements in a one-dimensional sorted array for a value, using the
IComparable<T> generic interface implemented by each element of the Array or a specified value.
Syntax: public static int BinarySearch<T> (T[] arr, int start, int len, T val);
Here, "T" is the type of the elements of the array.
Parameters:
arr: It is the one-dimensional sorted array to search for.
start: It is the starting index of the range to search.
len: It is the length of the range to search.
val: It is the object to search for.
Return Value: It returns the index of the specified
valin the specified
arr if the
val is found otherwise it returns a negative number. There are different cases of return values as follows:
- If the val is not found and valis less than one or more elements in the arr, the negative number returned is the bitwise complement of the index of the first element that is larger than val.
- If the val is not found and val is greater than all elements in the arr, the negative number returned is the bitwise complement of (the index of the last element plus 1).
- If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if the val is present in the arr.
Exceptions:
- ArgumentNullException: If array is null.
- InvalidOperationException: If T does not implement the IComparable<T> generic interface.
- ArgumentException: If start and len do not specify a valid range in array or value is of a type that is not compatible with the elements of array.
- ArgumentOutOfRangeException: If start is less than the lower bound of array.
Example:
csharp
// C# program to demonstrate the use of
// BinarySearch<T>(T[], Int32, Int32,
// T) method
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
int[] arr = { 1, 5, 3, 4, 2, 7 };
Console.WriteLine("Original Array");
foreach(int g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nAfter Sort");
// sort the array
Array.Sort(arr);
foreach(int g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nBinarySearch for '6':");
// search for "6" in a
// range of index 0 to 4
int index = Array.BinarySearch(arr, 0, 4, 6);
sort(arr, index);
}
// BinarySearch<T> method
private static void sort<T>(T[] array, int index)
{
if (index < 0) {
// If the index is negative,
// it represents the bitwise
// complement of the next
// larger element in the array.
index = ~index;
Console.Write("Sorts between: ");
if (index == 0)
Console.Write("beginning of array and ");
else
Console.Write("{0} and ", array[index - 1]);
if (index == array.Length)
Console.WriteLine("end of array");
else
Console.WriteLine("{0}", array[index]);
}
else
{
Console.WriteLine("Found at index {0}", index);
}
}
}
Output:
Original Array
1
5
3
4
2
7
After Sort
1
2
3
4
5
7
BinarySearch for '6':
Sorts between: 4 and 5
BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>) Method
This method searches a range of elements in a one-dimensional sorted array for a value, using the specified IComparer<T> generic interface.
Syntax: public static int BinarySearch<T> (T[] array, int start, int len, T val, IComparer<T> comparer);
Here, "T" is the type of the elements of the array.
Parameters:
arr: It is the one-dimensional sorted array to search for.
start: It is the starting index of the range to search.
len: It is the length of the range to search.
value: It is the object to search for.
comparer: It is the IComparer<T> implementation to use when comparing elements.
Return Value: It returns the index of the specified
valin the specified
arr if the
val is found otherwise it returns a negative number. There are different cases of return values as follows:
- If the val is not found and valis less than one or more elements in the arr, the negative number returned is the bitwise complement of the index of the first element that is larger than val.
- If the val is not found and val is greater than all elements in the arr, the negative number returned is the bitwise complement of (the index of the last element plus 1).
- If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if the val is present in the arr.
Exceptions:
- ArgumentNullException: If array is null.
- InvalidOperationException: If T does not implement the IComparable<T> generic interface.
- ArgumentException: If start and len do not specify a valid range in array or comparer is null and val is of a type that is not compatible with the elements of array.
- ArgumentOutOfRangeException: If start is less than the lower bound of array or len is less than zero.
Example:
csharp
// C# program to demonstrate the use of
// BinarySearch<T>(T[], Int32, Int32,
// T, IComparer<T>) method
using System;
using System.Collections.Generic;
class comparer : IComparer<string> {
public int Compare(string x, string y)
{
return x.CompareTo(y);
}
}
class GFG {
// Main Method
public static void Main()
{
string[] arr = {"ABC", "UVW", "JKL",
"DEF", "MNO", "XYZ"};
Console.WriteLine("Original Array");
foreach(string g in arr)
{
Console.WriteLine(g);
}
// IComparer<T> object
comparer gg = new comparer();
Console.WriteLine("\nAfter Sort");
// sort the array
Array.Sort(arr, gg);
foreach(string g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nBinarySearch for 'GHI':");
// search for "GHI"
// search happens in the
// range of index 1 to 4
int index = Array.BinarySearch(arr, 1, 4, "GHI", gg);
sort(arr, index);
}
// BinarySearch<T> method
private static void sort<T>(T[] array, int index)
{
if (index < 0) {
// If the index is negative,
// it represents the bitwise
// complement of the next
// larger element in the array.
index = ~index;
Console.Write("Sorts between: ");
if (index == 0)
Console.Write("beginning of array and ");
else
Console.Write("{0} and ", array[index - 1]);
if (index == array.Length)
Console.WriteLine("end of array");
else
Console.WriteLine("{0}", array[index]);
}
else
{
Console.WriteLine("Found at index {0}", index);
}
}
}
Output:
Original Array
ABC
UVW
JKL
DEF
MNO
XYZ
After Sort
ABC
DEF
JKL
MNO
UVW
XYZ
BinarySearch for 'GHI':
Sorts between: DEF and JKL
Reference:
Similar Reads
Introduction
C# TutorialC# (pronounced "C-sharp") is a modern, versatile, object-oriented programming language developed by Microsoft in 2000 that runs on the .NET Framework. Whether you're creating Windows applications, diving into Unity game development, or working on enterprise solutions, C# is one of the top choices fo
4 min read
Introduction to .NET FrameworkThe .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The .NET framework is primarily used on Windows, while .NET Core (which evolved into
6 min read
C# .NET Framework (Basic Architecture and Component Stack)C# (C-Sharp) is a modern, object-oriented programming language developed by Microsoft in 2000. It is a part of the .NET ecosystem and is widely used for building desktop, web, mobile, cloud, and enterprise applications. This is originally tied to the .NET Framework, C# has evolved to be the primary
6 min read
C# Hello WorldThe Hello World Program is the most basic program when we dive into a new programming language. This simply prints "Hello World!" on the console. In C#, a basic program consists of the following:A Namespace DeclarationClass Declaration & DefinitionClass Members(like variables, methods, etc.)Main
4 min read
Common Language Runtime (CLR) in C#The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others.When a C# program is compiled, th
4 min read
Fundamentals
C# IdentifiersIn programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name, or label. Example: public class GFG { static public void Main () { int
2 min read
C# Data TypesData types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C# each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given pr
7 min read
C# VariablesIn C#, variables are containers used to store data values during program execution. So basically, a Variable is a placeholder of the information which can be changed at runtime. And variables allows to Retrieve and Manipulate the stored information. In Brief Defination: When a user enters a new valu
4 min read
C# LiteralsIn C#, a literal is a fixed value used in a program. These values are directly written into the code and can be used by variables. A literal can be an integer, floating-point number, string, character, boolean, or even null. Example:// Here 100 is a constant/literal.int x = 100; Types of Literals in
5 min read
C# OperatorsIn C#, Operators are special types of symbols which perform operations on variables or values. It is a fundamental part of language which plays an important role in performing different mathematical operations. It takes one or more operands and performs operations to produce a result.Types of Operat
7 min read
C# KeywordsKeywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to be used as variable names or objects. Doing this will result in a compile-time error.Example:C#// C# Program to illustrate the
5 min read
Control Statements
C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of program based on certain conditions. These
5 min read
C# Switch StatementIn C#, Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type.
4 min read
C# LoopsLooping in a programming language is a way to execute a statement or a set of statements multiple times, depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops.Types of Loops in C#Loops are mainly divided
4 min read
C# Jump Statements (Break, Continue, Goto, Return and Throw)In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. In, this article, we will learn to different jump statements available to work in C#.Types of Jump StatementsThere are mainly five keywords in th
4 min read
OOP Concepts
Methods
Arrays
C# ArraysAn array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array spe
8 min read
C# Jagged ArraysA jagged array is an array of arrays, where each element in the main array can have a different length. In simpler terms, a jagged array is an array whose elements are themselves arrays. These inner arrays can have different lengths. Can also be mixed with multidimensional arrays. The number of rows
4 min read
C# Array ClassArray class in C# is part of the System namespace and provides methods for creating, searching, and sorting arrays. The Array class is not part of the System.Collections namespace, but it is still considered as a collection because it is based on the IList interface. The Array class is the base clas
7 min read
How to Sort an Array in C# | Array.Sort() Method Set - 1Array.Sort Method in C# is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method as follows:Sort<T>(T[]) MethodSort<T>(T[], IComparer<T>) MethodSort<T>(T[], Int32, Int32) MethodSort<T>(T[], Comparison<T>) Method
8 min read
How to find the rank of an array in C#Array.Rank Property is used to get the rank of the Array. Rank is the number of dimensions of an array. For example, 1-D array returns 1, a 2-D array returns 2, and so on. Syntax: public int Rank { get; } Property Value: It returns the rank (number of dimensions) of the Array of type System.Int32. B
2 min read
ArrayList
String
Tuple
Indexers