yan061

导航

java 二分法查找数组

二分法适用于有序的序列

public static void dichotomy(int num){
        int[] li = {-2,-1,0,1,2,3,4,5,6,7,8,9};
        int start = 0;
        int end = li.length -1;
        boolean isFind = false;

        while (start <= end){
            int middle = (start + end) / 2;

            if (num == li[middle]){
                System.out.println("找到了,索引是"+middle);
                isFind = true;
                break;
            }else if (num > li[middle]){
                start = middle + 1;
            }else {
                end = middle -1;
            }
        }
        if (!isFind){
            System.out.println("抱歉没有找到");
        }
    }

    public static void main(String[] args) {
        dichotomy(7);
    }

  

posted on 2022-01-06 14:35  yan061  阅读(38)  评论(0编辑  收藏  举报