In: Computer Science
Make a Binary search program for C# and write algorithm and explain it in easy words also show output and input
using System;
class Bin {
private static int binarySearch(int[] inputArray, int x)
{
int left = 0, right = inputArray.Length - 1;
while (left <= right) {
int midpoint = left + (right - left) / 2; //midpoint
// initital check to be done at mid point
if (inputArray[midpoint] == x)
return midpoint;
if (inputArray[midpoint] < x) // check in the right half of tree
left = midpoint + 1;
else
right = midpoint - 1; // check in the let half of tree
}
return -1;
}
public static void Main()
{
int[] inputArray = { 1, 33, 15, 11, 54 };
int find = 1;
int testResult = binarySearch(inputArray, find);
if (testResult == -1) Console.WriteLine("Cannot find Element");
else Console.WriteLine("Element found at " + "index " + testResult);
}
}