首页 > 其他 > 详细

编程之美书摘

时间:2017-01-03 07:55:19      阅读:102      评论:0      收藏:0      [点我收藏+]
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;
            }
        }

 

编程之美书摘

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!