利用递归实现折半查找

static void Main(string[] args)
{
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int index = BinarySearch(array, 0, array.Length,5);
Console.WriteLine(index);
}
//利用递归实现折半查找
注意集合一定是要有序的,如果不是要对集合西先进行排序然后在查找
public static int BinarySearch(int[] arr, int low, int high, int key)
{
Console.WriteLine(“——-“);
int mid = (low + high) / 2;
if (low > high)
return -1;
else
{
if (arr[mid] == key)
return mid;
else if (arr[mid] > key)
{

                return BinarySearch(arr, low, mid - 1, key);
            }
            else
            {

                return BinarySearch(arr, mid + 1, high, key);
            }

        }
    }

你可能感兴趣的:(利用递归实现折半查找)