I have implemented a binary search algorithm in C#. Can anyone give me suggestions on improving its effectiveness?
using System;
namespace bs2
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
for(int i=0;i<n;i++)
{
arr[i] = i*14; //14 is a random number, I multiply by a number so that arr[i] would not be equal to i.
}
int searchingfor = int.Parse(Console.ReadLine());
int min = 0;int max = n-1;int mid = (n-1)/2;
while (true)
{
if (arr[mid] == searchingfor)
{
Console.WriteLine("Element is on position {0}", mid);
break;
}else if (arr[mid] < searchingfor)
{
min = mid;
mid = (min + max) / 2;
}else if (arr[mid] > searchingfor)
{
max = mid;
mid = (min + max) / 2;
}
}
}
}
}
Array
andList<T>
classes have aBinarySearch
method, right? That one won't have the overflow bug your code does. I assume you are reinventing this wheel for strictly pedagogical purposes? \$\endgroup\$