dzWatching
2020-10-10 22:55
采纳率: 60%
浏览 180
已采纳

请问二分法我这里使用的for循环的循环条件(i < arr.length / 2)有问题吗?


```package com.watching.contact;

public class QueryTest2 {
    public static void main(String[] args) {
        //二分法查找需要数列有序
        int[] arr = new int[] {1,2,3,4,5,25,99,574,1000};
        int dest = 5;
        int head = 0;//首索引
        int end = arr.length - 1;//末索引
        boolean isflag = true;
        for(int i = 0;i < arr.length / 2;i++) {
            int middle = (head + end) / 2;
            if (arr[middle] == dest) {
                System.out.println("恭喜你找到了" + dest + "!它在数组的第" + middle + "个位置!");
                isflag = false;
                break;
                }
                else if(arr[middle] < dest) {
                    head = middle + 1;
            } 
                else end = middle - 1;
        }
            if(isflag == true) {
                System.out.println("抱歉,没在数组中找到你想找的数~");
            }
    }
}

1条回答 默认 最新

相关推荐 更多相似问题