Loading

java 二分法

源码

public class Dichotomy {
    public static void  main(String[] args){
        int[] array = new int[12];
        for(int i=0;i<12;i++){
            array[i] = i;
        }

        System.out.print(dichotomy(array,8));
    }

    private static int dichotomy(int[] array,int key){
        int left = 0,right = array.length-1;
        int t;
        while (left<=right){
            t = (left + right)/2;
            System.out.println("left"+left);
            System.out.println("right"+right);
            System.out.println(t);
            if(array[t] == key){
                return t;
            }
            if(array[t] < key){
                left = t+1;
            }
            if(array[t] > key){
                right = t-1;
            }
        }
        return -1;
    }
}
posted @ 2019-02-21 21:53  李帆1998  阅读(199)  评论(0编辑  收藏  举报