0
How do I implement a binary search using c#
C#
2 odpowiedzi
0
Please show what you have tried so far
0
class BinarySearch
 {
 public static int Find(int[] numList, int val)
 {
int low = 0;
 int high = numList.Length-1;
 int mid = 0;
 while (low < =high)
 {
 Console.WriteLine(string.Format("low=0,high={1}",low,high));
 mid = high +low/ 2;
if (val == numList[mid])
 {
 Console.WriteLine(string.Format("found value"));
 return mid;
 }
 if (val > numList[mid])
 {
 Console.WriteLine(string.Format("value is less than the middle element"));
 low = mid + 1;
Console.WriteLine(string.Format("low=0,high={1},mid={2}", low, high, mid));
 }
 else
 {
 Console.WriteLine(string.Format("value is greater than the middle element"));
 high = mid - 1;
 }
}
return -1;
}
 }
 
 
public static void Main()
 {
 var location = BinarySearch.Find(new int[] { 1, 2, 3, 4,5,6,7,8,9 }, 6);
 Console.WriteLine(location);
}



