How to use Array.BinarySearch() Method In C#

Implement binary search in C# using Array class. How to use Array.BinarySearch() method on an array to find an item in the array.

Binary search, also known as half-interval search, is one of the common search algorithms that find the position of a value within a sorted array. The search algorithm looks for a value in a sorted array and starts at the middle element and compares the value with the item of the array. If the value is less than the element, search moves to the left side and starts at the middle element of the array. If the value is greater than the element, search moves to the right side and starts at the middle element of the array.

Note

This article was originally published on Jan 10, 2000. This is an updated article.
 
Here an article on how to use a binary search algorithm in C# without using any class.

The Array class in .NET framework supports several methods to search, sort, and reverse array items. Array.BinarySearch() method searches an an array of elements for the given element and returns the postion of the element found in the array.

The following code example creates an array of numbers and look for number 17 in the array and return its position. If no element is found, the method returns a negative value. 
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         // Create an array of 10 elements    
  6.         int[] IntArray = new int[10] { 1, 3, 5, 7, 11, 13, 17, 19, 23, 31 };  
  7.         // Value to search for    
  8.         int target = 17;  
  9.         int pos = Array.BinarySearch(IntArray, target);  
  10.         if (pos >= 0)  
  11.             Console.WriteLine($"Item {IntArray[pos].ToString()} found at position {pos + 1}.");  
  12.         else  
  13.             Console.WriteLine("Item not found");  
  14.         Console.ReadKey();  
  15.     }  
  16. }  
Binary Search in C# Array
Note:
  • The array must be sorted before calling the BinarySearch method.
  • This method does not support searching arrays that contain negative indexes.
  • If the Array does not contain the specified value, the method returns a negative integer. 
  • Either value or every element of array must implement the IComparable interface, which is used for comparisons. The elements of array must already be sorted in increasing value according to the sort order defined by the IComparable implementation; otherwise, the result might be incorrect.
  • Duplicate elements are allowed. If more than one matched elements found in the array, the method returns the index of only one of the occurrences, and not necessarily the first one. 

Further Readings

Here is a list of some related articles: