Binary Search Algorithm in C# (min, max, middle position)
class BinarySearch
{
public static int Find(List<int> list, int searched)
{
//First sort input
BucketSort.Execute(list, ShellSort.Execute);
//Find min position
int min = 0;
//Find max position
int max = list.Count - 1;
int loops = 0;
do
{
//Find middle position
int middle = (min + max) / 2;
if (searched < list[middle])
{
//Bring down max so we half the search span the next time.
max = middle - 1;
}
else if (searched > list[middle])
{
//Bring up min so we can half the search span the next time.
min = middle + 1;
}
else
{
Console.WriteLine($"Loop Counter: {loops}");
//This is the item
return middle;
}
loops++;
}
while (min <= max);
Console.WriteLine($"Loop Counter: {loops}");
return -1;
}
}
{
public static int Find(List<int> list, int searched)
{
//First sort input
BucketSort.Execute(list, ShellSort.Execute);
//Find min position
int min = 0;
//Find max position
int max = list.Count - 1;
int loops = 0;
do
{
//Find middle position
int middle = (min + max) / 2;
if (searched < list[middle])
{
//Bring down max so we half the search span the next time.
max = middle - 1;
}
else if (searched > list[middle])
{
//Bring up min so we can half the search span the next time.
min = middle + 1;
}
else
{
Console.WriteLine($"Loop Counter: {loops}");
//This is the item
return middle;
}
loops++;
}
while (min <= max);
Console.WriteLine($"Loop Counter: {loops}");
return -1;
}
}
Comments
Post a Comment