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

编程之美书摘

时间:2017-01-03 07:58:13      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:mini   循环   class   bis   lin   string   否则   search   ret   

static void Main(string[] args)
        {
            char[] arr = new[] { a, b, c, d, e};
            char v = d;
            var index = BiSearch(arr, 0, 4, v);
            Console.WriteLine(index);

            char[] arr2 = new[] {  b, c, d, e, f };
            char v2 = a;
            var index2 = BiSearch(arr2, 0, 4, v2);
            Console.WriteLine(index2);
            Console.Read();
        }


        static int BiSearch(char[] arr, int b, int e, char v)
        {
            int minIndex = b, maxIndex = e, midIndex;

            //循环结束有两种情况:
            //若minIndex为偶数则minIndex == maxIndex
            //否则就是minIndex == maxIndex - 1
            while (minIndex < maxIndex - 1)
            {
                midIndex = minIndex + (maxIndex - minIndex)/2;
                if (arr[midIndex].CompareTo(v) <= 0)
                {
                    minIndex = midIndex;
                }
                else
                {
                    //不需要midIndex - 1,防止minIndex == maxIndex
                    maxIndex = midIndex;
                }
            }

            if (arr[maxIndex].CompareTo(v) == 0)
            {
                return maxIndex;
            }
            else if (arr[minIndex].CompareTo(v) == 0)
            {
                return minIndex;
            }
            else
            {
                return -1;
            }
        }

 

编程之美书摘

标签:mini   循环   class   bis   lin   string   否则   search   ret   

原文地址:http://www.cnblogs.com/hellolong/p/6243551.html

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