递归搜索新项目在排序列表中的位置?
我正在尝试实现一个搜索方法,该方法返回一个对象的索引,该对象应该递归地插入到排序列表中。
这是我的尝试。
//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 。
I'm trying to implement a search method, which returns a index of a object where it should be inserted in a sorted list, recursively.
Here is my attempt.
//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++);
}
For some reason I seem to be getting a StackOverflowError
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当你说
index++
的效果是“增加索引,然后返回index
曾经拥有的值。”这意味着传递到递归调用中的index
值将与原始调用中的值相同。我认为您想将其更改为读取哪个更正确地将
index + 1
的值传递到search
中。这里可能还有其他错误,但这肯定会导致问题。尝试改变这个,看看会发生什么。
希望这有帮助!
When you're saying
The effect of
index++
is "increment index, then hand back the value thatindex
used to have." This means that the value ofindex
passed into the recursive call will be the same as in the original call. I think you want to change this to readWhich more correctly passes the value of
index + 1
intosearch
.There may be other errors here, but this certainly is going to cause problems. Try changing this and see what happens.
Hope this helps!
您是否忘记了必须在索引之前插入的情况?如果值< sortedList[index] 你的方法将无休止地递归地调用自身...
编辑:
如果你修复了“index++”错误,你现在应该看到应该在开头插入的值的不正确行为列表中的内容,将被附加。
Didn't you forget the case, that you have to insert before index? If value < sortedList[index] your method will call itself recursively endlessly...
EDIT:
If you fix your "index++" bug, you should now see the incorrect behavior that values that are supposed to be inserted at the beginning of the list, would instead be appended.