在C#中實(shí)現(xiàn)遞歸的二分查找可以通過編寫一個(gè)遞歸函數(shù)來實(shí)現(xiàn)。下面是一個(gè)使用遞歸方式實(shí)現(xiàn)二分查找的示例代碼:
using System;
class BinarySearch
{
public static int RecursiveBinarySearch(int[] array, int target, int min, int max)
{
if (min > max)
{
return -1;
}
int mid = (min + max) / 2;
if (array[mid] == target)
{
return mid;
}
else if (array[mid] < target)
{
return RecursiveBinarySearch(array, target, mid + 1, max);
}
else
{
return RecursiveBinarySearch(array, target, min, mid - 1);
}
}
static void Main()
{
int[] array = { 2, 5, 8, 12, 16, 23, 38, 56, 72, 91 };
int target = 23;
int result = RecursiveBinarySearch(array, target, 0, array.Length - 1);
if (result != -1)
{
Console.WriteLine("Element found at index: " + result);
}
else
{
Console.WriteLine("Element not found in the array");
}
}
}
在上面的示例代碼中,定義了一個(gè)RecursiveBinarySearch
函數(shù)來實(shí)現(xiàn)遞歸的二分查找。在函數(shù)中,首先判斷最小索引是否大于最大索引,如果是則返回-1表示未找到目標(biāo)值。然后計(jì)算中間索引,如果中間值等于目標(biāo)值,則返回中間索引,否則根據(jù)中間值與目標(biāo)值的大小關(guān)系遞歸調(diào)用函數(shù)繼續(xù)查找左半部分或右半部分。在Main
函數(shù)中調(diào)用RecursiveBinarySearch
函數(shù)并輸出結(jié)果。