• 编程之美书摘


    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;
                }
            }
  • 相关阅读:
    从hadoop框架与MapReduce模式中谈海量数据处理
    Hadoop
    Clone Graph
    Gas Station
    ZigZag Conversion
    String to Integer (atoi)
    Palindrome Number
    Container With Most Water
    Longest Common Prefix
    求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)
  • 原文地址:https://www.cnblogs.com/hellolong/p/6243551.html
Copyright © 2020-2023  润新知