【问题标题】:Recursively search for where new item goes inside sorted list?递归搜索新项目在排序列表中的位置?
【发布时间】:2012-02-08 08:31:22
【问题描述】:

我正在尝试实现一个搜索方法,该方法返回一个对象的索引,它应该递归地插入到排序列表中。

这是我的尝试。

 //listSize is the number of elements inside the sorted list 
 //sortedList is the actual structure holding the values
 // Note: the parameter Value is comparable.  
 public int search(T value,int index){

    if(listSize == 0){
        return 0;
    }
    if(index > listSize){
        return listSize+1; //add at the end
    }
    if(value.compareTo(sortedList[index]) > 0 && value.compareTo(sortedList[index+1]) < 0){
        //value is less 
        return index+1;
    }else if(value.compareTo(sortedList[index]) == 0){
        //both are same
        return index+1;
    }
    return search(value,index++);
}

由于某种原因,我似乎收到了StackOverflowError

【问题讨论】:

  • 即使你修复了由 templatetypedef 正确识别的错误,你仍然会遇到在列表中为每个元素使用堆栈帧的问题,所以你仍然会遇到问题每当您的列表大于几千个元素时。看到列表实际上是如何排序的,您可能想要实现二进制搜索。

标签: java recursion sortedlist


【解决方案1】:

当你说的时候

return search(value,index++);

index++ 的作用是“增加索引,然后将index 曾经拥有的值交还”。这意味着传递给递归调用的index 的值将与原始调用中的值相同。我想你想把它改成阅读

return search(value, index + 1);

哪个更正确地将index + 1 的值传递给search

这里可能还有其他错误,但这肯定会导致问题。尝试更改此设置,看看会发生什么。

希望这会有所帮助!

【讨论】:

  • ++index 也应该这样做。
  • 哈哈不敢相信我犯了这个错误!
  • @Nishant- 是的,但由于index 是一个即将超出范围的局部变量,我认为没有任何理由在这里使用++index。副作用是误导性的,对代码的细微调整(回到index++)会破坏它。
【解决方案2】:

你没有忘记必须在 索引之前插入的情况吗?如果 value

编辑

如果您修复了“index++”错误,您现在应该会看到应该在列表开头插入的值反而被追加的错误行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多