课后作业07--二分法查找算法代码

            Console.Write("请输入数组的长度:");
            int k = int.Parse(Console.ReadLine());
            int[] arr1 = new int[k];
            Console.Write("数组包含值依次为:");
            for (int i = 0; i < k; i++)//数组赋值
            {
                Random rd = new Random();
                int j = rd.Next(100);
                Thread.Sleep(200);
                arr1[i] = j;
                Console.Write(j + " ");
            }
            int s;

            Console.Write("\n您要查找的数为: ");
            try
            {
                s = Convert.ToInt32(Console.ReadLine());
            }
            catch
            {
                Console.WriteLine("您输入有误!请按回车退出");
                Console.ReadLine();
                return;
            }
            Console.WriteLine("数组从小到大排列:");
            //数组排序
            for (int i = k - 1; i > 0; i--)
            {
                for (int j = 0; j <= k -2; j++)
                {
                    if (arr1[j] > arr1[j + 1])
                    {
                        int m = arr1[j];
                        arr1[j] = arr1[j + 1];
                        arr1[j + 1] = m;
                    }
                }
            }
            for (int i = 0; i <= k -1; i++)
            {
                Console.Write(arr1[i] + " ");
            }
            int a = 0, b = k -1;
            while (arr1[(a + b) / 2] != s)//二分法 
            {
                if (arr1[a] == s || arr1[b] == s || b - a == 1)
                    break;

                while (arr1[(a + b) / 2] > s)
                {
                    if (arr1[b] == s )
                        break;
                    b = (a + b) / 2;
                }
                while (arr1[(a + b) / 2] < s)
                {
                    if (arr1[a] == s || b - a == 1)//当输入数组不含有的数字,利用b-a判断可跳出循环
                        break;
                    a = (a + b) / 2;
                }
            }
            if (arr1[(a + b) / 2] == s)
                Console.Write("\n您查找的数是数组的第" + ((a + b) / 2 + 1) + "位!");
            else if (arr1[a] == s)
                Console.Write("\n您查找的数是数组的第" + (a + 1) + "位!");
            else if (arr1[b] == s)
                Console.Write("\n您查找的数是数组的第" + (b + 1) + "位!");
            else
                Console.Write("\n您输入的数字不存在!");
            Console.ReadLine();

 

posted @ 2015-08-09 22:53  WhyToHow  阅读(195)  评论(0编辑  收藏  举报