我试图实现一个搜索方法,它返回一个对象的索引,它应该被递归地插入到一个排序列表中。递归搜索新项目在排序列表中的位置?
这是我的尝试。
//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
。
你应该使用'++ index'吗? – Nishant 2012-02-08 08:36:03
即使您修正了由templatetypedef正确标识的错误,您仍然会遇到问题,即您在列表中每个元素都使用了一个堆栈框架,所以只要您的列表大于某个列表,您仍然会遇到问题几千个元素。看看列表是如何分类的,你可能会想要实现一个二分法搜索。 – Dolda2000 2012-02-08 09:22:50