【问题标题】:Recursion binary search for a double-ordered array [closed]双序数组的递归二进制搜索[关闭]
【发布时间】:2021-03-14 15:18:01
【问题描述】:

给定一组n 不同的数字,这些数字从索引0 严格增加到m,并从索引m 严格减少到索引n-1,我想使用递归来找到索引@数组中最大数的 987654328@。我的方法需要按比例运行O(log n)

到目前为止,我一直在考虑使用二进制搜索递归算法,它确实会在我相信的给定时间复杂度下运行,并提出了以下内容;

/* 
 * @param inputArr     -> input array of numbers over which the reccursive method is called 
 * @param head   -> the first index of the array passed as argument
 * @param tail     -> the last index of the array passed as argument
 * @returns max    -> index for the maximum of the ascending sequence
 */
public static int largestNumber(int[] inputArr, int head, int tail) {
    //base cases for recursion to stop
    if(head==tail)
        return head;

    int midIndex = (tail + head)/2;
    
    // the maximum is at the mid index
    if(inputArr[midIndex] > inputArr[midIndex +1] && inputArr[midIndex] < inputArr[midIndex -1]) {
        return midIndex;
    } else {
        
        // the maximum is not at the mid index
        if (inputArr[midIndex+1] > inputArr[midIndex]) {
            return largestNumber(inputArr, midIndex+1, tail);
        } else {
            return largestNumber(inputArr, head, midIndex - 1);
        }
    }

这个的输出是

这些都是不正确的(从上到下应该是0 , 3, 2, 4),表明我对基本情况或条件语句的处理不当。有人对我可能出错的地方或我遗漏了什么情况有任何暗示吗?在我看来,我的功能似乎已经完成了......

【问题讨论】:

    标签: java recursion binary-search


    【解决方案1】:

    我看到的一件事是,您在比较 inputArr[midIndex] &gt; inputArr[midIndex - 1]inputArr[midIndex] &lt; inputArr[midIndex - 1]。要返回最大值,您希望inputArr[midIndex] 大于两边的元素。

    head == 0tail == 1 时,您还访问了非法数组索引。

    【讨论】:

      猜你喜欢
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 2019-01-19
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      相关资源
      最近更新 更多