【问题标题】:Convert binary search to use recursion将二进制搜索转换为使用递归
【发布时间】:2021-10-16 07:57:20
【问题描述】:

我在我的程序中实现了这个二分搜索算法,它实现了 Comparator 接口。本质上,我想让这个方法递归,但我一直没有这样做。我想知道这样做是否合适。

public static <Key> int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
    if (a == null || key == null || comparator == null) {
        throw new NullPointerException("Arguments cannot be null.");
    }
    int low = 0,
        high = a.length - 1;
    if (comparator.compare(a[0], key) == 0) {
        return 0;   // Non-recursive base case.
    }
    while (low <= high) {
        int mid = low + (high - low) / 2;
        // For key, we are searching for the first occurrence.
        // Comparator: compare the key is being sorted with.
        if (comparator.compare(key, a[mid]) < 0) high = mid - 1;
        else if (comparator.compare(key, a[mid]) > 0) low = mid + 1;
        else if (comparator.compare(a[mid - 1], a[mid]) == 0) high = mid - 1;
        
        else return mid;
    }
    return -1;      // Index of the first occurrence of an element matching key in a[].
}

【问题讨论】:

  • 1) 你试过什么? 2)它可能是合适的,但如果迭代方式有效,那你为什么要这样做?
  • 代码工作得非常好,但我想我开始倾向于让我的大部分方法递归。感谢您将问题更改为更合适的内容,也感谢您回复。
  • 这很好,但你到底有哪些尝试“失败”了?你得到什么错误?您对流程有哪些具体问题?
  • 注意 - 递归解决方案更有可能出现堆栈溢出错误。如果有一个简单的迭代解决方案更可取。

标签: java arrays binary-search


【解决方案1】:

您将highlow 传递给该方法。创建采用这些附加参数的方法的另一个版本,将其设为private 并使用0a.length - 1 调用它以获取新参数。喜欢,

public static <Key> int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
    return firstIndexOf(a, key, comparator, 0, a.length - 1);
}

然后简单地用递归调用替换循环。喜欢,

private static <Key> int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator, int low, int high) {
    if (a == null || key == null || comparator == null) {
        throw new NullPointerException("Arguments cannot be null.");
    }
    if (comparator.compare(a[0], key) == 0) {
        return 0; // Non-recursive base case.
    }
    if (low <= high) {
        int mid = low + (high - low) / 2;
        // For key, we are searching for the first occurrence.
        // Comparator: compare the key is being sorted with.
        if (comparator.compare(key, a[mid]) < 0)
            return firstIndexOf(a, key, comparator, low, mid - 1);
        else if (comparator.compare(key, a[mid]) > 0)
            return firstIndexOf(a, key, comparator, mid+1, high);
        else if (comparator.compare(a[mid - 1], a[mid]) == 0)
            return firstIndexOf(a, key, comparator, low, mid - 1);
        else
            return mid;
    }
    return -1; // Index of the first occurrence of an element matching key in a[].
}

【讨论】:

    猜你喜欢
    • 2018-08-28
    • 2012-03-20
    • 2012-04-19
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多