How to use Array.BinarySearch() Method in C# | Set -1
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.
Important Points:
- Before calling this method, the array must be sorted.
- This method will return the negative integer if the array doesn't contain the specified value.
- The array must be one-dimensional otherwise this method can't be used.
- The Icomparable interface must be implemented by the value or every element of the array.
- The method will return the index of only one of the occurrences if more than one matched elements found in the array and it is not necessary that index will be of the first occurrence.
There are total 8 methods in the overload list of this method as follows:
- BinarySearch(Array, Object)
- BinarySearch(Array, Object, IComparer)
- BinarySearch(Array, Int32, Int32, Object)
- BinarySearch(Array, Int32, Int32, Object, IComparer)
- BinarySearch<T>(T[], T)
- BinarySearch<T>(T[], T, IComparer<T>)
- BinarySearch<T>(T[], Int32, Int32, T)
- BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>)
This method is used to search a specific element in the entire 1-D sorted array. It used the IComparable interface that is implemented by each element of the 1-D array and the specified object. This method is an O(log n) operation, where n is the Length of the specified array.
Syntax: public static int BinarySearch (Array arr, object val);
Parameters:
arr: It is the sorted 1-D array 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 the arr is null.
- RankException: If the arr is multidimensional.
- ArgumentException: If the val is of a type which is not compatible with the elements of the arr.
- InvalidOperationException: If the val does not implement the IComparable interface, and the search encounters an element that does not implement the IComparable interface.
Below programs illustrate the above-discussed method:
Example 1:
C#
// C# program to illustrate the
// Array.BinarySearch(Array, Object)
// Method
using System;
class GFG {
// Main Method
public static void Main(String[] args)
{
// taking an 1-D Array
int[] arr = new int[7] { 1, 5, 7, 4, 6, 2, 3 };
// for this method array
// must be sorted
Array.Sort(arr);
Console.Write("The elements of Sorted Array: ");
// calling the method to
// print the values
display(arr);
// taking the element which is
// to search for in a variable
// It is not present in the array
object s = 8;
// calling the method containing
// BinarySearch method
result(arr, s);
// taking the element which is
// to search for in a variable
// It is present in the array
object s1 = 4;
// calling the method containing
// BinarySearch method
result(arr, s1);
}
// containing BinarySearch Method
static void result(int[] arr2, object k)
{
// using the method
int res = Array.BinarySearch(arr2, k);
if (res < 0) {
Console.WriteLine("\nThe element to search for "
+ "({0}) is not found.",
k);
}
else {
Console.WriteLine("The element to search for "
+ "({0}) is at index {1}.",
k, res);
}
}
// display method
static void display(int[] arr1)
{
// Displaying Elements of array
foreach(int i in arr1)
Console.Write(i + " ");
}
}
Output: The elements of Sorted Array: 1 2 3 4 5 6 7
The element to search for (8) is not found.
The element to search for (4) is at index 3.
Example 2:
C#
// C# program to illustrate the
// Array.BinarySearch(Array, Object)
// Method
using System;
class GFG {
// Main Method
public static void Main(String[] args)
{
// taking an 1-D Array
int[] arr = new int[7] { 1, 5, 7, 4, 6, 2, 3 };
// for this method array
// must be sorted
Array.Sort(arr);
Console.Write("The elements of Sorted Array: ");
// calling the method to
// print the values
display(arr);
// it will return a negative value as
// 9 is not present in the array
Console.WriteLine("\nIndex of 9 is: " + Array.BinarySearch(arr, 9));
}
// display method
static void display(int[] arr1)
{
// Displaying Elements of array
foreach(int i in arr1)
Console.Write(i + " ");
}
}
Output: The elements of Sorted Array: 1 2 3 4 5 6 7
Index of 9 is: -8
This method is used to search a specific element in the entire 1-D sorted array using the specified IComparer interface.
Syntax: public static int BinarySearch(Array arr, Object val, IComparer comparer)
Parameters:
arr : The one-dimensional sorted array in which the search will happen.
val : The object value which is to search for.
comparer : When comparing elements then the IComparer implementation is used.
Return Value: It returns the index of the specified val in 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 val is 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.
- RankException: If arr is multidimensional.
- ArgumentException: If the range is less than lower bound OR length is less than 0.
- ArgumentException: If the comparer is null, and value is of a type that is not compatible with the elements of arr.
- InvalidOperationException: If the comparer is null, value does not implement the IComparable interface, and the search encounters an element that does not implement the IComparable interface.
Example:
C#
// C# program to demonstrate the
// Array.BinarySearch(Array,
// Object, IComparer) Method
using System;
class GFG {
// Main Method
public static void Main()
{
// initializes a new Array.
Array arr = Array.CreateInstance(typeof(Int32), 5);
// Array elements
arr.SetValue(20, 0);
arr.SetValue(10, 1);
arr.SetValue(30, 2);
arr.SetValue(40, 3);
arr.SetValue(50, 4);
Console.WriteLine("The original Array");
// calling "display" function
display(arr);
Console.WriteLine("\nsorted array");
// sorting the Array
Array.Sort(arr);
display(arr);
Console.WriteLine("\n1st call");
// search for object 10
object obj1 = 10;
// call the "FindObj" function
FindObj(arr, obj1);
Console.WriteLine("\n2nd call");
object obj2 = 60;
FindObj(arr, obj2);
}
// find object method
public static void FindObj(Array Arr,
object Obj)
{
int index = Array.BinarySearch(Arr, Obj,
StringComparer.CurrentCulture);
if (index < 0) {
Console.WriteLine("The object {0} is not found\nNext"
+ " larger object is at index {1}",
Obj, ~index);
}
else {
Console.WriteLine("The object {0} is at index {1}",
Obj, index);
}
}
// display method
public static void display(Array arr)
{
foreach(int g in arr)
{
Console.WriteLine(g);
}
}
}
Output: The original Array
20
10
30
40
50
sorted array
10
20
30
40
50
1st call
The object 10 is at index 0
2nd call
The object 60 is not found
Next larger object is at index 5
This method is used to search a value in the range of elements in a 1-D sorted array. It uses the IComparable interface implemented by each element of the array and the specified value. It searches only in a specified boundary which is defined by the user.
Syntax: public static int BinarySearch(Array arr, int i, int len, object val);
Parameters:
arr: It is 1-D array in which the user have to search for an element.
i: It is the starting index of the range from where the user want to start the search.
len: It is the length of the range in which the user want to search.
val: It is the value which the user to search for.
Return Value: It returns the index of the specified val in 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 val is 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.
- RankException: If arr is multidimensional.
- ArgumentOutOfRangeException: If the index is less than lower bound of array OR length is less than 0.
- ArgumentException: If the index and length do not specify the valid range in array OR the value is of the type which is not compatible with the elements of the array.
- InvalidOperationException: If value does not implement the IComparable interface, and the search encounters an element that does not implement the IComparable interface.
Example:
C#
// C# Program to illustrate the use of
// Array.BinarySearch(Array, Int32,
// Int32, Object) Method
using System;
using System.IO;
class GFG {
// Main Method
static void Main()
{
// initializing the integer array
int[] intArr = { 42, 5, 7, 12, 56, 1, 32 };
// sorts the intArray as it must be
// sorted before using method
Array.Sort(intArr);
// printing the sorted array
foreach(int i in intArr) Console.Write(i + " "
+ "\n");
// intArr is the array we want to find
// and 1 is the starting index
// of the range to search. 5 is the
// length of the range to search.
// 32 is the object to search
int index = Array.BinarySearch(intArr, 1, 5, 32);
if (index >= 0) {
// if the element is found it
// returns the index of the element
Console.WriteLine("Index of 32 is : " + index);
}
else {
// if the element is not
// present in the array or
// if it is not in the
// specified range it prints this
Console.Write("Element is not found");
}
// intArr is the array we want to
// find. and 1 is the starting
// index of the range to search. 5 is
// the length of the range to search
// 44 is the object to search
int index1 = Array.BinarySearch(intArr, 1, 5, 44);
// as the element is not present
// it prints a negative value.
Console.WriteLine("Index of 44 is :" + index1);
}
}
Output: 1
5
7
12
32
42
56
Index of 32 is : 4
Index of 44 is :-7
This method is used to search a value in the range of elements in a 1-D sorted array using a specified IComparer interface.
Syntax: public static int BinarySearch(Array arr, int index, int length, Object value, IComparer comparer)
Parameters:
arr : The sorted one-dimensional Array which is to be searched.
index : The starting index of the range from which searching will start.
length : The length of the range in which the search will happen.
value : The object to search for.
comparer : When comparing elements then use the IComparer implementation.
Return Value: It returns the index of the specified value in the specified arr, if the value is found otherwise it returns a negative number. There are different cases of return values as follows:
- If the value is not found and value is less than one or more elements in the array, the negative number returned is the bitwise complement of the index of the first element that is larger than value.
- If the value is not found and value is greater than all elements in the array, 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 value is present in the array.
Example: In this example, here we use "CreateInstance()" method to create a typed array and stores some integer value and search some values after sort the array.
C#
// C# program to demonstrate the
// Array.BinarySearch(Array,
// Int32, Int32, Object,
// IComparer) Method
using System;
class GFG {
// Main Method
public static void Main()
{
// initializes a new Array.
Array arr = Array.CreateInstance(typeof(Int32), 8);
// Array elements
arr.SetValue(20, 0);
arr.SetValue(10, 1);
arr.SetValue(30, 2);
arr.SetValue(40, 3);
arr.SetValue(50, 4);
arr.SetValue(80, 5);
arr.SetValue(70, 6);
arr.SetValue(60, 7);
Console.WriteLine("The original Array");
// calling "display" function
display(arr);
Console.WriteLine("\nsorted array");
// sorting the Array
Array.Sort(arr);
display(arr);
Console.WriteLine("\n1st call");
// search for object 10
object obj1 = 10;
// call the "FindObj" function
FindObj(arr, obj1);
Console.WriteLine("\n2nd call");
object obj2 = 60;
FindObj(arr, obj2);
}
// find object method
public static void FindObj(Array Arr,
object Obj)
{
int index = Array.BinarySearch(Arr, 1, 4,
Obj, StringComparer.CurrentCulture);
if (index < 0) {
Console.WriteLine("The object {0} is not found\n"
+ "Next larger object is at index {1}",
Obj, ~index);
}
else {
Console.WriteLine("The object {0} is at "
+ "index {1}",
Obj, index);
}
}
// display method
public static void display(Array arr)
{
foreach(int g in arr)
{
Console.WriteLine(g);
}
}
}
Output: The original Array
20
10
30
40
50
80
70
60
sorted array
10
20
30
40
50
60
70
80
1st call
The object 10 is not found
Next larger object is at index 1
2nd call
The object 60 is not found
Next larger object is at index 5
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