Binary Search In C#

Binary search, also known as half-interval search is one of the common search algorithms that finds the positon 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.

The Array class in .NET framework supports several methods to search, sort, and reverse an array items. In this article, we will use the BinarySearch method of the Array class to search an array items using the binary search algorithm.

  1. using System;  
  2. using System.Data.OleDb;  
  3. class Program  
  4. {  
  5. static void Main(string[] args)  
  6. {  
  7. // Create an array of 10 elements  
  8. int[] IntArray = new int[10] { 1, 3, 5, 7, 11, 13, 17, 19, 23, 31 };  
  9. // Value to search for  
  10. int target = 17;  
  11. int pos = Array.BinarySearch(IntArray, target);  
  12. if (pos >= 0)  
  13. Console.WriteLine("Item {0} found at position {1}.", IntArray[pos].ToString(), pos + 1);  
  14. else  
  15. Console.WriteLine("Item not found");  
  16. Console.ReadKey();  
  17. }  
  18. }  

 

Further Readings

Here is a list of some related articles: