当搜索传递的数组中不存在的单词时,该函数将导致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
问题是,如果你在二进制搜索数组时,你要么递增或递减高,所以如果你要搜索的字不在数组中,则只会继续递增直到它超过高值。
对不起,如果我误解了你的问题。