Array.BinarySearch(Array, Int32, Int32, Object) Method with examples in C#


The Array.BinarySearch() method in C# is used to searches a range of elements in a one-dimensional sorted array for a value, using the IComparable interface implemented by each element of the array and by the specified value.

Note − It searches in a sorted array.

Syntax

The syntax is as follows −

public static int BinarySearch (Array arr, int index, int len, object val);

Above, the parameters arr is the 1-D array to search, index is the beginning index of the range to search, len is the length of the search. The val parameter is the object to search for.

Example

Let us now see an example −

 Live Demo

using System;
public class Demo {
   public static void Main() {
      int[] intArr = {10, 20, 30, 40, 50};
      Array.Sort(intArr);
      Console.WriteLine("Array elements...");
      foreach(int i in intArr) {
         Console.WriteLine(i);
      }
      Console.Write("Element 20 is at index = " + Array.BinarySearch(intArr, 1, 3, 20));
   }
}

Output

This will produce the following output −

Array elements...
10
20
30
40
50
Element 20 is at index = 1

Example

Let us now see another example −

 Live Demo

using System;
public class Demo {
   public static void Main() {
      int[] intArr = {5, 10, 15, 20};
      Array.Sort(intArr);
      Console.WriteLine("Array elements...");
      foreach(int i in intArr) {
         Console.WriteLine(i);
      }
      Console.Write("Element 25 is at index = " + Array.BinarySearch(intArr, 0, 2, 20));
   }
}

Output

This will produce the following output −

Array elements...
5
10
15
20
Element 25 is at index = -3
raja
Published on 04-Dec-2019 09:28:41
Advertisements