怎么能快速的找到你想要的索引(二分法)

你如何查询自己想要的数据?
直接用索引遍历查询。如果数据很多呢?比如:100万、1000万、100百万?你要全部遍历完需要多久?会不会一直卡在这里?那取一条数据我们也要去遍历,那会不会浪费资源?那我们就可以用二分法进行解决问题:

class Program
    {
        static void Main(string[] args)
        {
            #region 二分法
            int[] array = new int[1000];
            for (int i = 0; i < 1000; i++)
            {
                array[i] = i;
            }
            Console.WriteLine(binaryQuery(array, 786));
            #endregion
            Console.ReadLine();
        }

        public static int binaryQuery(int []array,int target)
        {
            int start = 0; //开始值

            int end = array.Length - 1;  //结束值
            int middle;  //中间值
            while(start<=end)
            {
                middle = start + (end - start) / 2;
                if(array[middle] ==target)
                {
                    return middle;
                }
                else if(array[middle] <target)
                {
                    start = middle + 1;
                    Console.WriteLine(array[middle] +":小了");
                }
                else
                {
                    end = middle - 1;
                    Console.WriteLine(array[middle] + ":大了");
                }
            }
            return -1;
        }
    }
View Code

 

posted @ 2019-07-08 09:59  走过不远的地方  阅读(288)  评论(0编辑  收藏  举报