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.
- using System;
- using System.Data.OleDb;
- 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 {0} found at position {1}.", IntArray[pos].ToString(), pos + 1);
- else
- Console.WriteLine("Item not found");
- Console.ReadKey();
- }
- }
Further Readings
Here is a list of some related articles: