二分法

来源:互联网 发布:电子商务就业前景知乎 编辑:程序博客网 时间:2024/05/19 13:21

class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Random rd = new Random();
                const int Number = 20;
                var demoData = new List<int>();
                for (int i = 0; i < Number; i++)
                    demoData.Add(rd.Next(10, 100));
                var array = demoData.OrderBy(c => c).ToArray();
                Console.WriteLine("源数据:{0}", string.Join(" ", array));
                Console.WriteLine("请输入要搜索的数:");
                var a = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine(BinarySearch(array, a));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("\nAny key to continue...");
            Console.ReadKey();
        }

        static string BinarySearch(int[] array, int x)
        {
            int left = 0, right = array.Length - 1;
            int middle, tryTimes = 0;
            if (x > array[array.Length - 1] || x < array[0]) return string.Format("给定的集合中没有:{0},搜索次数:0", x);

            while (left < right)
            {
                tryTimes++;
                middle = (left + right) / 2;
                if (x == array[middle]) return string.Format("{0}的索引是:{1},搜索次数:{2}", x, middle, tryTimes);
                if (x > array[middle]) left = middle + 1;
                else right = middle - 1;
            }

            return string.Format("给定的集合中没有:{0},搜索次数:{1}", x, tryTimes);
        }
    }