码迷,mamicode.com
首页 > 其他好文 > 详细

二分法查找

时间:2015-03-02 06:06:28      阅读:370      评论:0      收藏:0      [点我收藏+]

标签:

#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

 

二分法查找

标签:

原文地址:http://www.cnblogs.com/lihonglin2016/p/4307871.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!