二分查找法

 public static int dichotomySearch(int[] array,int a){
        System.out.println("正在执行方法");
        int start=0;
        int length=array.length-1;
        int index;
        while (start<=length){
            System.out.println("start="+start);

            index=(start+length)/2;//中间位置
            System.out.println("index="+index);
            System.out.println("length="+length);
            if(array[index]==a){
                return index+1;
            }else if(array[index]<a){
                //向右查找
                start=index+1;
            }else {
                //向左查找
                length=index-1;
            }
        }
        return -1;
    }

  

  public static void main(String[] args) {
        int[] arrays={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,26,27,28,29,30,31,32,33,34,35,36,37,38,39,39,40};

        int input=39;
       System.out.println("位置等于"+dichotomySearch(arrays,input));

        /**
         * 正在执行方法
         * start=0
         * pot=19
         * length=39
         * start=20
         * pot=29
         * length=39
         * start=30
         * pot=34
         * length=39
         * start=35
         * pot=37
         * length=39
         * start=38
         * pot=38
         * length=39
         * 位置等于39
         */
    }

  

posted @ 2023-02-04 18:28  郎小乐  阅读(14)  评论(0编辑  收藏  举报