二分查找

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Bsearch
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr={1,2,3,4,5,6,7,8,9,10,11};//二分查找的对象是一个已经有序的顺序表
            int r = Bsearch(arr,11);
            Console.WriteLine(r);
            Console.WriteLine(Array.BinarySearch(arr,11));
        }
        public static int Bsearch(int[] arr,int key)
        {
            int low = 0, high = arr.Length - 1;
            while (low <= high)
            {
                int mid = (low + high)>> 1;//Array内部的二叉查找就是通过右移来实现整除
                if (key == arr[mid]) return mid;
                else if (key < arr[mid])
                    high = mid - 1;
                else
                    low = mid + 1;
            }
            return ~low;
            //当所查找的值不存在的时候,low指针会指向一个合适的查找关键字的插入位置,为了既能表示查找的关键字不存在
            //又能保存查找关键字的插入点,所以返回low的补码。这样当查找失败是得时候既能返回一个负值,又能再次对返回
            //值求补得到插入点信息进行插入操作。

        }
    }
   

}

 

相关文章:

  • 2021-06-15
  • 2022-01-27
  • 2022-12-23
  • 2021-11-09
  • 2022-12-23
  • 2022-02-16
  • 2021-12-20
  • 2022-01-07
猜你喜欢
  • 2021-10-15
  • 2021-12-11
  • 2021-09-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-23
相关资源
相似解决方案