Java面试题 二分查找(有序数组)

二分查找(有序数组)

必须是有序的数组

package QFTest;

public class Test_16 {
     
    public static void main(String[] args) {
     
        int[] arrs={
     3,4,5,33,222,1111,3333};
        int key=33;
        int result=binarySearch(arrs,key);
        System.out.println(result);
    }
    public static int binarySearch(int[] arrs,int key){
     
        int low=0;
        int high=arrs.length-1;
        while(low<=high){
     
            int temp=(low+high)/2;
            if(arrs[temp]<key){
     
                low=temp+1;
            }else if(arrs[temp]>key){
     
                high=temp-1;
            }else{
     
                return temp+1;
            }
        }
        return -1;
    }
}
//答案
4

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