小编rji*_*z52的帖子

二进制搜索数组给出错误的值

我正在对数组进行二进制搜索.但有些事情要关闭.它返回-1,好像没有找到目标但是它在数组中.例如:当我将键放在555时,它返回正确的索引但是当我尝试使用下面的例子时,它返回-1 ..

public class bSearch {

    public static void main(String[] args) {
        int[] nums = {9,5,2,5,7,8,3,22,555};
        int key = 8;

        System.out.println(searchForNum(nums,0,nums.length-1,key));
    }

    private static int searchForNum(int[] arr,int first, int last, final int target) {
        int middle= (first+last)/2;

        if(last < first) {
            return -1;
        }

        if(arr[middle]== target)
            return middle;
        else if(target < arr[middle]) {
            return searchForNum(arr,first,middle-1,target);
        } else {
            return searchForNum(arr,middle+1,last,target);
        }  
    }

}
Run Code Online (Sandbox Code Playgroud)

java algorithm binary-search

-3
推荐指数
1
解决办法
75
查看次数

标签 统计

algorithm ×1

binary-search ×1

java ×1