java 利用二分查找查找目标数的索引

iyr7buue  于 2023-04-28  发布在  Java
关注(0)|答案(2)|浏览(77)

这是我第一次利用这个平台提问。我想知道下面的代码有什么问题,它们没有在main的末尾打印出目标数字的索引。怎么了?祝阅读这篇文章的人有一个美好的一天。

public class binarySearch {
    public static void main(String[] args) {
        Scanner keyboard=new Scanner(System.in);
        int target,index;
        int [] numArray={1,4,6,7,8,10,14,16,17,26,30,35,38,41};

        System.out.print("What do you want to find?");
        target=keyboard.nextInt();
        index=binarySearch(numArray, target);
        System.out.println("The element is found at index:"+index);
    }

    static int binarySearch(int [] numArray, int target){
        int left=0;
        int right=numArray.length-1;
        int mid=(left+right)/2;
        while(left<=right){
            if(numArray[mid]==target){
                return mid;
            }else if(target<numArray[mid]){
                right=mid-1;
            }else{
                left=mid+1;
            }
        }
        return -1;
    }
}
gzjq41n4

gzjq41n41#

你没有重新计算,mid在循环内:

static int binarySearch(int [] numArray, int target) {
    int left = 0;
    int right = numArray.length - 1;
    int mid = (left + right) / 2;
    while (left <= right) {
        mid= (left + right) / 2;
        if (numArray[mid] == target) {
            return mid;
        } else if (target < numArray[mid]) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return -1;
}
oyxsuwqo

oyxsuwqo2#

while条件后的初始中间值

public class binarySearch {
    public static void main(String[] args) {
        Scanner keyboard=new Scanner(System.in);
        int target,index;
        int [] numArray={1,4,6,7,8,10,14,16,17,26,30,35,38,41};

        System.out.print("What do you want to find?");
        target=keyboard.nextInt();
        index=binarySearch(numArray, target);
        System.out.println("The element is found at index:"+index);
    }

    static int binarySearch(int [] numArray, int target){
        int left=0;
        int right=numArray.length-1;
        while(left<=right){
            int mid=left+(right-left)/2;
            if(numArray[mid]==target){
                return mid;
            }else if(target<numArray[mid]){
                right=mid-1;
            }else{
                left=mid+1;
            }
        }
        return -1;
    }
}

相关问题