当搜索传递的数组中不存在的单词时,该函数将在我抛出自定义异常之前引发 StackOverflow。我不想在“应该”找到单词之前对平均迭代次数进行硬编码。
public int recSearch(String[] words, String wordToFind) throws ItemNotFoundException {
if (count == 0) {
low = 0;
high = words.length - 1;
}
count = 1;
super.incrementCount();
mid = (low + high) / 2;
if (mid <= 0)
throw new ItemNotFoundException("Item not found");
if (words[mid].equals(wordToFind))
return mid;
else if (words[mid].compareTo(wordToFind) < 0) {
low = mid + 1;
} else {
high = mid - 1;
}
return recSearch(words, wordToFind);
}
最佳答案
我不确定我是否正确理解了这些问题,但如果你的意思是条件mid <= 0
不会引发异常,并且函数会继续运行,直到导致 StackOverFlow,然后只需使用此条件即可:low >= high
问题是,当您对数组进行二进制搜索时,您要么递增 low ,要么递减 high ,所以如果您要搜索的单词不在数组中,则 low 将继续递增,直到它超过 high 的值。
抱歉,如果我误解了您的问题。
关于java - 作业问题: Need just a hint for the base case to throw an exception for a recursive binary search when a word doesn't exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54840489/