递归搜索新项目在排序列表中的位置?

时间:2012-02-08 08:31:23

标签: java recursion sortedlist

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

这是我的尝试。

 //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

2 个答案:

答案 0 :(得分:1)

当你说

return search(value,index++);

index++的效果是&#34;增量索引,然后交回index曾经拥有的值。&#34;这意味着传递给递归调用的index的值将与原始调用中的值相同。我想你想改变这个来阅读

return search(value, index + 1);

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

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

希望这有帮助!

答案 1 :(得分:0)

你有没有忘记这个案例,你必须在索引之前插入?如果值< sortedList [index]你的方法将无休止地递归调用自己...

修改

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