【发布时间】:2021-06-14 17:21:48
【问题描述】:
我写了一个递归二进制搜索方法,如果字典中存在这个词,它就可以工作,但是,当我输入一个不存在的词时,比如“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
}
【问题讨论】:
-
当你进入调用这个的循环时,你认为会发生什么? return wordCheck(target, middle + 1, end);你会陷入无限循环
-
什么是
end?最后一个元素的索引,还是最后一个元素的索引加一?换句话说,要在完整列表中搜索,您会调用wordCheck(target, 0, words.size())还是wordCheck(target, 0, words.size()-1)?
标签: java binary-search