- 废话不多说,直接上代码
static void Main(string[] args)
{
//定义数组
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7 };
//方法一:使用递归方法实现
int result1 = BinaryRecursion(array, 0, array.Length - 1, 3);
//方法二:使用while循环实现
int result2 = BinaryWhile(array, 0, array.Length - 1, 3);
Console.WriteLine(result1);
Console.WriteLine(result2);
}
/// <summary>
/// 二分查找:递归方法
/// </summary>
/// <param name="array">数组</param>
/// <param name="low">开始索引</param>
/// <param name="high">结束索引</param>
/// <param name="key">要查找的目标对象</param>
/// <returns>返回索引</returns>
static int BinaryRecursion(int[] array, int low, int high, int key)
{
//中间索引
int mid = (low + high) / 2;
if (low > high)
{
return -1;
}
else
{
if (array[mid] == key)
//当中间索引等于目标对象时,直接返回
return mid;
else if (array[mid] > key)
//当中间索引大于目标对象时,结束索引左移
return BinaryRecursion(array, low, mid - 1, key);
else
//当中间索引小于目标对象时,开始索引右移
return BinaryRecursion(array, mid + 1, high, key);
}
}
/// <summary>
/// 二分查找:while循环
/// </summary>
/// <param name="array">数组</param>
/// <param name="low">开始索引</param>
/// <param name="high">结束索引</param>
/// <param name="key">要查找的目标对象</param>
/// <returns>返回索引</returns>
static int BinaryWhile(int[] array, int low, int high, int key)
{
while (low <= high)
{
//中间索引
int mid = (low + high) / 2;
if (array[mid] == key)
//当中间索引等于目标对象时,直接返回
return mid;
else if (array[mid] > key)
//当中间索引大于目标对象时,结束索引左移
high = mid - 1;
else if (array[mid] < key)
//当中间索引小于目标对象时,开始索引右移
low = mid + 1;
}
return -1;
}