簡體   English   中英

當單詞不存在時,遞歸二進制搜索返回 stackoverflow 錯誤

[英]Recursive binary search returning a stackoverflow error when word doesn't exist

我寫了一個遞歸二進制搜索方法,如果字典中存在這個詞,它就可以工作,但是,當我輸入一個不存在的詞時,比如“rwetjia”,我得到一個stackoverflow錯誤

    public boolean wordCheck(String target, int start, int end) {
    target.toLowerCase();
    if (end >= 1) {
        int middle = start + (end - start) / 2;
        int targetside = target.compareTo(words.get(middle));// Finds which side the word is on
        if (targetside == 0) {
            return true;
        } // Word is at the middle (the word exists and has been found)
        else if (targetside > 0) {
            return wordCheck(target, middle + 1, end);
        } // If target word is on the right side of the array, "cuts" the other half off
        else {
            return wordCheck(target, start, middle - 1);
        }
    } // If target word is on the left side of the array, "cuts" the other half off
        return false; // Word is not in the dictionary
}

嘗試:

if (end >= start) {

代替

if (end >= 1) {

更新:

我假設end是要考慮的最后一個元素的索引(請參閱我上面的評論); 否則,測試將是:

if (end > start) {

你需要更換:

        return wordCheck(target, start, middle - 1);

和:

        return wordCheck(target, start, middle);

問題是你的結束條件,即“end >= 1”。 例如,假設您輸入的單詞比列表中的任何單詞都小。 在我的示例中,現在我在某個地方,start = 3 和 end = 10。這為您提供了以下迭代:

Iteration. Start - End - Middle
1. 3 - 10 - 6.5
2. 6 - 10 - 8
3. 9 - 10 - 9.5
4. 10 - 10 - 10
5. 11 - 10 - 10.5

你需要做的是檢查我猜是否“開始<=結束”。 我沒有考慮過這個例子,例如它更小,但我認為它應該涵蓋所有情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM