How to use Array.BinarySearch() Method in C# | Set -2
Last Updated :
14 Mar, 2022
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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
Decorators in Python In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Sliding Window Technique Sliding Window Technique is a method used to solve problems that involve subarray or substring or window. The main idea is to use the results of previous window to do computations for the next window. This technique is commonly used in algorithms like finding subarrays with a specific sum, finding t
13 min read