我想看看是否有人能指出我在这个正确的方向,我觉得我可以忽略一些非常简单的东西,主要是在约45,000字的列表上调用搜索方法,我相信是这个问题,我的代码适用于列表中前6个或上千个单词的单词,但在此之后它遇到StackOverflow错误并崩溃。我有一个非递归的版本,工作正常。递归线性搜索 - StackOverflowError
我有两个基本案例,它们是数组的末尾,在这种情况下,我们抛出ItemNotFoundException,并且如果找到该单词,则返回该条目所在的索引。
我当前的代码是:
工作正常public int search(String[] words, String wordToFind)
throws ItemNotFoundException {
return search(words, wordToFind, 0);
}
private int search(String[] words, String wordToFind, int index) {
incrementCount();
if(index == words.length) {
// If index gets to the end of the array, then the word is not in the array
throw new ItemNotFoundException();
}
if (words[index].equals(wordToFind)) {
// If word is found, return the index.
return index;
} else {
// Increment index by 1
index++;
// Call the search again
return search(words, wordToFind, index);
}
}
非递归码:
public int search(String[] words, String wordToFind)
throws ItemNotFoundException {
int count = 0;
for (String word : words) {
incrementCount();
if (word.equals(wordToFind)) {
return count;
}
count++;
}
throw new ItemNotFoundException();
}
为什么当一个简单的循环可以完成这项工作时使用递归?顺便说一句,你是_“非递归代码”_是递归的,因为你粘贴了相同的代码两次。 –
同意。对于这种大型列表的搜索类型,使用循环来完成这项工作而不是递归更好。只有在更方便的情况下才使用递归。实际上,所有递归算法都可以用非递归算法替代。 – tonga
我只是试图以递归方式做这件事,因为这是在作业中指定的。我在帖子中修复了非递归的代码。 – user3357667