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


The Array.BinarySearch(Array, Object) method in C# is used to search an entire one-dimensional sorted array for a specific element, using the IComparable interface implemented by each element of the array and by the specified object.

Syntax

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

Above, arr is the sorted 1-D array, whereas val is the object to search for.

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, 20));
   }
}

Output

Array elements...
5
10
15
20
Element 25 is at index = 3

Example

 Live Demo

using System;
public class Demo {
   public static void Main() {
      string[] strArr = {"John", "Tim", "Fedric", "Gary", "Harry", "Damien"};
      Array.Sort(strArr);
      Console.WriteLine("Array elements...");
      foreach(string s in strArr) {
         Console.WriteLine(s);
      }
      Console.Write("Element Gary is at index = " + Array.BinarySearch(strArr, "Gary"));
      Console.Write("
Element Tom is at index = " + Array.BinarySearch(strArr, "Tom"));    } }

Output

Array elements...
Damien
Fedric
Gary
Harry
John
Tim
Element Gary is at index = 2
Element Tom is at index = -7

Updated on: 03-Dec-2019

127 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements