温馨提示×

如何在C#中使用泛型实现二分查找

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

下面是一个使用泛型实现二分查找的例子:

using System;

class BinarySearch<T> where T : IComparable
{
    public static int Search(T[] array, T value)
    {
        int min = 0;
        int max = array.Length - 1;

        while (min <= max)
        {
            int mid = (min + max) / 2;

            if (array[mid].CompareTo(value) == 0)
            {
                return mid;
            }
            else if (array[mid].CompareTo(value) < 0)
            {
                min = mid + 1;
            }
            else
            {
                max = mid - 1;
            }
        }

        return -1;
    }
}

class Program
{
    static void Main()
    {
        int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int value = 5;

        int index = BinarySearch<int>.Search(array, value);

        if (index != -1)
        {
            Console.WriteLine($"Value {value} found at index {index}");
        }
        else
        {
            Console.WriteLine($"Value {value} not found in array");
        }
    }
}

在这个例子中,我们使用泛型 T 来表示数组和要查找的值的类型。我们要求 T 必须实现 IComparable 接口,以便能够使用 CompareTo 方法来比较两个对象。然后我们定义了一个 BinarySearch 类,其中包含一个静态方法 Search,该方法接受一个数组和要查找的值,并返回该值在数组中的索引(如果存在)或 -1(如果不存在)。在 Main 方法中,我们创建了一个整数数组,并使用 BinarySearch 类来查找值 5 在数组中的位置。

0