Recursive search error

时间:2016-10-20 20:10:32

标签: java if-statement for-loop recursion

running into a silly error and I just don't see it. I've been looking at this for a while and don't see what I'm missing. I am recursively searching an array for a specific target number but once I get up to element [7] it begins returning -1. Thanks for taking a look fellas/ladies!

    public static void main(String[] args) 
    {
        int[] a = {1,25,2,6,4,3,23,30,32,14,11,8};
        Arrays.sort(a);
        int target = a[7];
        int first = a[0];
        int last = a.length;
        for(int i=0;i<a.length;i++)
        {
            System.out.print(" "+a[i]);
    }
        System.out.println("\n"+binarySearch(target,first,last,a));
    }
    public static int binarySearch(int target,int first, int last, int[] a)
    {
        int result;
        if(first>last)
            return -1;
        else
        {
            int mid = (first+last)/2;
            if(target == mid)
                result = mid;
            else if(target<a[mid])
                result = binarySearch(target,first,last-1,a);
            else
                result = binarySearch(target,mid+1,last,a);

        }
        return result;
    }

1 个答案:

答案 0 :(得分:2)

在某些地方,您无法准确区分数组索引中的值和索引本身。

这个:a[i]获取第i个元素的值

这:i只是一个索引,我

考虑到这一点,这是您的代码的固定版本。请参阅我在代码中对我修复的一些特定错误的评论:

public static void main(String[] args) 
{
    int[] a = {1,25,2,6,4,3,23,30,32,14,11,8};
    Arrays.sort(a);
    int target = a[7];
//here you want the index of the first location to search, not the value in that index
//so you use 0 instead of a[0]
    int first = 0;
//the last element index is length-1, not length, since arrays are 0-based
    int last = a.length - 1;     
    for(int i=0;i<a.length;i++)
    {
        System.out.print(" "+a[i]);
    }
    System.out.println("\n"+binarySearch(target,first,last,a));
}

public static int binarySearch(int target,int first, int last, int[] a)
{
    int result;
    if(first>last)
        return -1;
    else
    {
        int mid = (first+last)/2;
//here you need to check if the target is equal to the value at the index mid
//before you were checking if the target was equal to the index, which was never true
        if(target == a[mid])
//you want to return the value at the target, not the index of the target
//so use a[mid] not mid
            result = a[mid];
        else if(target<a[mid])
//here you want to search from first to mid-1
//before you were searching from first to last-1, which is not correct binary search
            result = binarySearch(target,first,mid - 1,a);
        else
            result = binarySearch(target,mid + 1,last,a);

    }
    return result;
}