• 编程之美书摘


    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;
                }
            }
  • 相关阅读:
    easyui 如何引入
    图片切换展示效果
    渐变弹出层
    C# GEP基因化编程
    C#操作内存
    移动的彩虹
    收缩和展开效果
    用SQL语句,删除掉重复项只保留一条
    图片切换,带标题文字
    Sql Server快速建表
  • 原文地址:https://www.cnblogs.com/hellolong/p/6243551.html
Copyright © 2020-2023  润新知