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.
- class Program
- {
- static void Main(string[] args)
- {
-
- int[] IntArray = new int[10] { 1, 3, 5, 7, 11, 13, 17, 19, 23, 31 };
-
- int target = 17;
- int pos = Array.BinarySearch(IntArray, target);
- if (pos >= 0)
- Console.WriteLine($"Item {IntArray[pos].ToString()} found at position {pos + 1}.");
- else
- Console.WriteLine("Item not found");
- Console.ReadKey();
- }
- }
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: