温馨提示×

C#中如何实现递归的二分查找

c#
小樊
82
2024-08-21 08:46:30
栏目: 编程语言

在C#中实现递归的二分查找可以通过编写一个递归函数来实现。下面是一个使用递归方式实现二分查找的示例代码:

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");
        }
    }
}

在上面的示例代码中,定义了一个RecursiveBinarySearch函数来实现递归的二分查找。在函数中,首先判断最小索引是否大于最大索引,如果是则返回-1表示未找到目标值。然后计算中间索引,如果中间值等于目标值,则返回中间索引,否则根据中间值与目标值的大小关系递归调用函数继续查找左半部分或右半部分。在Main函数中调用RecursiveBinarySearch函数并输出结果。

0