二分法查找已排序数组中是否存在某值~

时间:2022-10-23 19:12:56

如题,一个二分法查找的使用实例。直接给出代码:

public class erfenTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a = {1,2,3,4,5,6};
        int key = 6;
        System.out.println(findkey(a,key));
        
    }
    
     public static int findkey(int[] a, int key) {
          int higher,middle,lower = 0;//头初始为0
          higher = a.length - 1;//尾长度
          while(higher>=lower){
                   middle = (lower + higher)/2;
                   if(key == a[middle]){
                    return middle;//查找到,返回数据位置。
                   }
                   else if(key > a[middle]){
                    lower = middle+1 ;//大于中间值,去后半段查找
                  }
                  else if(key < a[middle]){
                    higher = middle-1 ;//小于中间值,去前半段查找
                 }
          }
          return  -1;
     }
}