A binary search finds the position of a specified input value (the search "key") within an sorted array. In each step, the algorithm compares the search key value with the key value of the middle element of the array. If the keys match, then a matching element has been found and its index, or position, is returned. Otherwise, if the search key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right. If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not found" indication is returned.
using System;
namespace binary_search
{
class Program
{
static void Main(string[] args)
{
Program p = new Program(); //making object of class program
int n, x, temp, t;
int[] arr = new int[50];
Console.WriteLine("Enter no of elements you want to store in an array");
n = Convert.ToInt32(Console.ReadLine());
//Either enter element in sorted manner or we can apply any sorting technique to sort array
Console.WriteLine("Enter elements in an array");
for (int i = 1; i <= n; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
// sorting method to sort an array because it is neccessary condition for binary search that array should be sorted
//sorting method we are using here is insertion sort
for (int i = 1; i <= n; i++)
{
temp = arr[i];
t = i - 1;
while (t >= 0 && temp < arr[t])
{
arr[t + 1] = arr[t];
t--;
}
arr[t + 1] = temp;
}
// Dispalys sorted array
Console.WriteLine("array after sorting");
for (int i = 1; i <= n; i++)
{
Console.WriteLine(arr[i]);
}
// Enter Element you want to search in an array
Console.WriteLine("Enter element you want to search");
x = Convert.ToInt32(Console.ReadLine());
p.binarysearch(arr, 1, n, x); // calling method named binarysearch for performing search operation
Console.ReadKey();
}
public void binarysearch(int[] a, int i, int j, int x)
{
int mid;
while (i <= j)
{
mid = (i + j) / 2; // calculate mid
if (a[mid] == x) // check whether value at mid position is equal to value we are searching or not
{
Console.WriteLine("element {0} is found at pos {1}", x, mid); // if yes print message
break;
}
else if (a[mid] > x) // if not it checks whether value at mid position is greater than the value we are searching or not
j = mid - 1; // if yes control passes here
else
i = mid + 1; // else control passes here
}
}
}
}