二分法查找,C#小程序

SearchUtil类:

using System;
namespace searchdemo.Utils
{
    public class SearchUtil where T : struct, IComparable
    {
        public static int binarySearch(T[] table, T value, int low, int high)
        {
            while (low <= high)
            {
                int mid = (low + high) / 2;
                if (table[mid].Equals(value))
                {
                    return mid;
                }
                else if (table[mid].CompareTo(value) < 0)
                {
                    low = mid + 1;
                }
                else
                {
                    high = mid - 1;
                }
            }

            return -1;
        }

        public static int binarySearch(T[] table, T value)
        {
            int n = table.Length;
            return SearchUtil.binarySearchRec(table, value, 0, n - 1);
        }

        public static int binarySearchRec(T[] table, T value, int low, int high)
        {
            if (low > high)
            {
                return -1;
            }

            int mid = (low + high) / 2;
            if (table[mid].Equals(value))
            {
                return mid;
            }

            if (table[mid].CompareTo(value) < 0)
            {
                return SearchUtil.binarySearchRec(table, value, mid + 1, high);
            }
            else
            {
                return SearchUtil.binarySearchRec(table, value, low, mid - 1);
            }
        }
    }
}

主程序类:

using System;
using searchdemo.Utils;

namespace searchdemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] table = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
            int index = SearchUtil.binarySearch(table, 1);
            Console.WriteLine($"1在数组中的第{index}个位置");
        }
    }
}

程序输出如下:


1.png

你可能感兴趣的:(二分法查找,C#小程序)