【问题标题】:Recursive search error递归搜索错误
【发布时间】:2016-10-20 20:10:31
【问题描述】:

遇到了一个愚蠢的错误,我只是没有看到它。我已经看了一段时间了,看不出我错过了什么。我正在递归地搜索一个数组以查找特定的目标编号,但是一旦我到达元素 [7],它就会开始返回 -1。感谢各位看官/女士们!

    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;
    }

【问题讨论】:

  • 具体来说,当你计算mid的时候,你要计算的mid就是midindex。所以你不能使用像这样的值:(first+last)/2。你需要索引。正确的?想想想想......你会到达那里!

标签: java if-statement for-loop recursion


【解决方案1】:

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

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

这:i 只是一个索引,我

考虑到这一点,这里是您的代码的固定版本。有关我修复的一些特定错误,请参见代码中的 cmets:

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;
}

【讨论】:

  • 我试过这个..这不起作用它只是给我目标作为一个int而不是作为目标的索引
  • 我的意思是在你回答之前我有这个想法,但仍然不正确。
  • @JaredWaxler 我正在运行它,它返回 7,这是目标的索引。如果您说它输出不同的东西,请解释它为您输出什么。
  • 假设返回存在于 a[7] 而不是 7 的索引。
  • 排序后的数字14
猜你喜欢
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多