分治法---二分搜索技术

public class BinarySerch {

    private int[] ints;

    public BinarySerch(int[] ints) {
        this.ints = ints;
    }

    public int search(int target){
        int left=0;
        int right=ints.length-1;
        while(left<=right){
            int middle=(left+right)/2;
            if(target==ints[middle])
                return middle;
            if(target>ints[middle])
                left=middle+1;
            else 
                right=middle-1;
        }
        return -1;
    }
    public static void main(String[] args) {
        int[] ints={3,5,8,22,34,67,89,90};
        BinarySerch bs = new BinarySerch(ints);
        System.out.println(bs.search(33));
        System.out.println(bs.search(22));
    }

}
-1 3

你可能感兴趣的:(二分搜索技术)