折半查找

public class A{
 
    public static void main(String[] args){
 
        int[] nums={-1,1,3,19,55,66};  //降序  66 55  19  3  1  -1
 
        int num=66;
 
        int index=A.getIndex(nums,num);
 
        System.out.println(index);
 
    }
 

 
    //算法复杂度极高  遍历  n/2的数据取查找   折半查找 log2N
 
    public static int getIndex(int[] arr,int num){
 
        int min=0;
 
        int max=arr.length-1;
 
        while(min <=max){
 
            int mid=(min+max)/2;
 
            if(num == arr[mid]){
 
                return mid;
 
            }else if(num < arr[mid]){
 
                max=mid-1;
 
            }else{
 
                min=mid+1;
 
            }
 
        }
 
        return -1;
 
    }
 

 
}
posted @ 2019-05-27 23:59  Bronze-y  阅读(165)  评论(0编辑  收藏  举报