2014-02-26 62 views
1

我想看看是否有人能指出我在这个正确的方向,我觉得我可以忽略一些非常简单的东西,主要是在约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(); 

}

+1

为什么当一个简单的循环可以完成这项工作时使用递归?顺便说一句,你是_“非递归代码”_是递归的,因为你粘贴了相同的代码两次。 –

+0

同意。对于这种大型列表的搜索类型,使用循环来完成这项工作而不是递归更好。只有在更方便的情况下才使用递归。实际上,所有递归算法都可以用非递归算法替代。 – tonga

+0

我只是试图以递归方式做这件事,因为这是在作业中指定的。我在帖子中修复了非递归的代码。 – user3357667

回答

3

主要是调用的有关名单上的搜索方法45,000字,我相信这是问题

是的,单词列表
的巨大长度导致堆栈溢出。
这对很多单词都是正常的。

+0

好的,所以它可能不可能做到这一点,因为那么多的话呢? – user3357667

+0

这是正确的。你不能指望有45,000层嵌套的调用栈可以正常工作。 –

0

一次又一次遇到堆栈溢出的原因是您正在递归O(n)次,其中n是列表的大小。这意味着,对于列表中的每个元素,您都将一个函数调用分配给必须保留的程序堆栈,直到找到结果。这自然会限制您可以搜索的列表的大小。

对于较大的列表,您需要一个更有效的递归解决方案,如binary search