二分法查找数据

        private static void QueryByMid()

        {

            int[] array = new int[] { 23, 33, 34, 43, 67, 78, 79 };

            int low = 0;

            int high = array.Length - 1;//这句很重要,减1避免数组值比较时索引超出

            int mid = 0;

            int queryNum = 78;//待查找的数

            int queryIndex = -1;



            while (low <= high)

            {

                mid = (low + high) / 2;

                if (queryNum == array[mid])

                {

                    queryIndex = mid;

                    break;

                }

                else

                {

                    if (queryNum < array[mid])

                    {

                        high = mid - 1;

                    }

                    else

                    {

                        low = mid + 1;

                    }

                }

            }

            if (queryIndex == -1)

            {

                Console.WriteLine("没有查找到对应的数据");

            }

            else

            {

                Console.WriteLine("数据查找到的索引位置:" + queryIndex);

            }

        }

 

你可能感兴趣的:(二分法)