二分法查找

#region 二分法查找

        static void InitBinData()

        {

            const int n = 20;

            int[] a = new int[n];

            Random r = new Random();

            for (int i = 0; i < n; ++i)

            {

                a[i] = r.Next(1, 21);

                Console.Write("  " + a[i]);

            }

            Console.WriteLine();

            BubbleSort(a);

            for (int i = 0; i < n; ++i)

            {

                Console.Write("  " + a[i]);

            }

            Console.WriteLine();

            Console.WriteLine("请输入查找的值");

            int value = Convert.ToInt32(Console.ReadLine());

            bool isOK = Binsrch(a, n, value);

            

            Console.WriteLine("是否找到" + isOK);

        }

        static bool Binsrch( int[] a, int n, int value )

        {

            

            int start = 0;

            int end = n - 1;

            int mid = 0;



            while ( start <= end )

            {

                mid = ((start + end) >> 1);

                if ( value < a[mid] )

                {

                    end = mid - 1;

                }

                else if ( value > a[mid] )

                {

                    start = mid + 1;

                } 

                else

                {

                    return true;

                }

            }

            return false;

        }

        #endregion

 

你可能感兴趣的:(二分法)