I am an algo-newbie and this is my first attempt at writing binary search and it worked on the first try. But something about it tells me that its far from perfect. Please tell me how I can improve.
using System;
class Program
{
public static void Main()
{
int[] arr = { 40, 67, 34, 25, 65, 87, 23 };
//insertion sort
for (int i = 0; i < arr.Length; i++)
{
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
arr[j + 1] = key;
}
}
//printing
Console.WriteLine("Sorted Array");
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i] + " ");
}
void BinarySearch(int[] arr, int lowerIndex, int upperIndex, int v)
{
if (lowerIndex <= upperIndex)
{
int middleIndex = (lowerIndex + upperIndex) / 2;
if (v == arr[middleIndex])
{
Console.WriteLine("Found at " + middleIndex);
}
else if (v < arr[middleIndex])
{
BinarySearch(arr, lowerIndex, middleIndex - 1, v);
}
else if (v > arr[middleIndex])
{
BinarySearch(arr, middleIndex + 1, upperIndex, v);
}
else Console.WriteLine("Not found");
}
}
//Searching for 87
BinarySearch(arr, 0, arr.Length - 1, 87);
}
}
6.0.101and that comes with C#10 \$\endgroup\$BinarySearch(arr, 0, arr.length - 1, 42);does not give the effect I take to be intended. \$\endgroup\$