二分查找

import java.util.Arrays;
public class Test2 {
    public static void main(String[] args) {
        int[] a = {1,3,5,6,7,8,9,10,12,18,19,20,100};
        System.out.println(binarySearch(a, 9));
        System.out.println(Arrays.binarySearch(a, 9));
    }

    public static int binarySearch(int[] a, int res){
        int begin = 0;
        int end = a.length - 1;
        while(begin <= end){
            int mid = (begin + end) / 2;
            if(a[mid] > res){
                begin = mid + 1;
            }else if(a[mid] < res){
                end = mid - 1;
            }else{
                return mid;
            }
        }
        return -1;
    }
}

你可能感兴趣的:(java面试(算法))