using System;
public class HelloWorld
{
public static void Main()
{
int[] y = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
int loopCount = 0;
int rr = BinarySearch(y, 0, y.Length - 1, 13, ref loopCount);
Console.Write("查找次数{0} 索引{1}", loopCount, rr);
}
public static int BinarySearch(int[] arr, int startIndex, int endIndex, int key, ref int count)
{
count++;
int mid = (startIndex + endIndex) / 2;
if (startIndex > endIndex)
return -1;
else
{
if (arr[mid] == key)
return mid;
else if (arr[mid] > key)
return BinarySearch(arr, startIndex, mid - 1, key, ref count);
else
return BinarySearch(arr, mid + 1, endIndex, key, ref count);
}
}
}