java - 作业问题: Need just a hint for the base case to throw an exception for a recursive binary search when a word doesn't exist

标签 java recursion binary-search

当搜索传递的数组中不存在的单词时,该函数将在我抛出自定义异常之前引发 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/

相关文章:

java - 将数据库时间戳列映射到 UTC 日历 (JPA) 并通过 WebService (jax-ws) 将其作为 UTC 日期传递

java - 使用 GSON 序列化 BigDecimal 值

python - Python 中的递归二分查找

c++ - 理解 C++ 算法二进制搜索背后的工作原理的问题

arrays - Swift:使用二进制搜索在数组中找到最接近的值

java - Maven 不下载依赖项的 jar

java - 一个又一个对话框显示对话框 : HANGS

c++ - 使用 C++ 的递归线程使资源暂时不可用

python - 内存python

php - 理解 PHP/mysql 中的递归