C# Array - BinarySearch() Method



The C# Array BinarySearch() method searches a range of elements in a one-dimensional sorted array for a value using the specified IComparer interface, where IComparer is a method that compares two objects.

Syntax

Following is the syntax of the C# Array BinarySearch() method −

public static int BinarySearch(Array array, object value, IComparer comparer);

Parameters

This function accepts the following array −

  • Array: One dimensional sorted array to search.
  • object: the value to search for.
  • IComparer: Implementation of the IComparer interface to customize the comparison logic. If it is null the natural IComparer logic is used.

Return value

This function returns the index of the specified value if the value is found in the current array; otherwise, a negative number. If values are not found and the value is less than one or more elements in the array.

Example 1: Use BinarySearch() Without IComparer

Let us crate a basic example of the BinarySearch() method to display index value of the specified element −

using System;
class Program {
   static void Main() {
      int[] numbers = { 1, 2, 3, 4, 5 };
      int value_to_search = 4;
      int index = Array.BinarySearch(numbers, value_to_search);

      if (index >= 0) {
         Console.WriteLine("Index: " + index);
      }
      else {
         Console.WriteLine("Value not found. Insertion point: " + ~index);
      }
   }
}

Output

Following is the output −

Index: 3

Example 2: BinarySearch with Custom IComparer

The following example uses the BinarySearch() method with a custom icomparer to display the index of the specified value according to the specified comparer logic −

using System;
using System.Collections;

class DescendingComparer : IComparer {
   public int Compare(object x, object y) {
      return Comparer.Default.Compare(y, x);
   }
}

class Program {
   static void Main() {
      // Sorted array in des order
      int[] numbers = { 50, 40, 30, 20, 10 };
      int valueToFind = 30;

      int index = Array.BinarySearch(numbers, valueToFind, new DescendingComparer());

      if (index >= 0) {
         Console.WriteLine($"Value {valueToFind} found at index {index}.");
      }
      else {
         Console.WriteLine($"Value {valueToFind} not found. Insertion point: {~index}");
      }
   }
}

Output

Following is the output −

Value 30 found at index 2.

Example 3: When Value is not Found

This is another, example of theBinarySearch()method. When a value is not found this function returns the insertion index value based on the sorted array −

using System;
class Program {
   static void Main() {
      // Sorted array in des order
      int[] numbers = { 10, 20, 30, 40, 50 };
      int valueToFind = 25;
      
      int index = Array.BinarySearch(numbers, valueToFind, null);
      Console.WriteLine($"Insertion point: {~index}");
   }
}

Output

Following is the output −

Insertion point: 2

Example 4: BinarySearch in a String Array

Here, in this example, we search the string with a custom comparer using theBinarySearch()method −

using System;
using System.Collections;

class CaseInsensitiveComparer : IComparer {
   public int Compare(object x, object y) {
      string str1 = x as string;
      string str2 = y as string;

      if (str1 == null || str2 == null)
          throw new ArgumentException("Both arguments must be strings.");

      // Perform case-insensitive comparison
      return string.Compare(str1, str2, StringComparison.OrdinalIgnoreCase);
   }
}
class Program {
   static void Main() {
      string[] fruits = { "Apple", "Banana", "Grape", "Mango", "Orange" };
      string valueToSearch = "mango";

      int index = Array.BinarySearch(fruits, valueToSearch, new CaseInsensitiveComparer());

      if (index >= 0) {
         Console.WriteLine($"Value '{valueToSearch}' found at index {index}.");
      }
      else {
         Console.WriteLine($"Value '{valueToSearch}' not found. Insertion point: {~index}");
      }
   }
}

Output

Following is the output −

Value 'mango' found at index 3.
csharp_array_class.htm
Advertisements