【发布时间】: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