【问题标题】:finding a unknown with recursive Binary Search使用递归二分搜索找到未知数
【发布时间】:2020-11-05 11:00:42
【问题描述】:

所以,我正在开发一个旨在在排序数组中查找枢轴点的程序,并且我正在使用二进制搜索,因为它需要 OlogN 的大 O。我一直在做一些 JUnit 测试,我注意到我的代码没有返回正确的值。当我单步执行代码时,它会得到正确的值,但会继续运行,然后返回错误的答案?我已经做了很多笔和纸测试,理论上它应该返回数字。

我正在做的测试是检查如果索引位于中间左侧,程序将如何响应。 另外,当我进行测试以检查索引是否在中间的右侧时,我会得到无限递归?

我不是在寻求解决方案,而是指向某事或某处的指针,我可能会遗漏某事,因为作为编码人员,我意识到我可能很难批评自己的代码。

 * Author: XXX
 *
 * This program is designed to find the pivot point in an array sorted in ascending order
 * that is rotated at some pivot unknown to you beforehand.
 */


package algorithmAssignment;

public class pivotFinder {

    public static void main(String[] args) {

        // testing
        int[] arr = new int[] {26, 28, 32, 1, 5, 6, 9, 10, 22};
        
        int result = findPivot(arr, arr.length - 1, 0, arr.length/2);
        
        // expected index of 3
        System.out.println(result);

    }

    static int findPivot(int[] arr, int max, int min, int pivot) { // feeding in arr, max, min, and pivot point

        // base case
        if (max - min < 1) {
            return pivot;
        }

        // binary search
        if (arr[pivot] < arr[max]) {
            findPivot(arr, pivot, min, pivot / 2); // return the arr, the pivot as the new max, and the new pivot
        } else {
            findPivot(arr, max, pivot, max - (pivot / 2)); // return the arr, the pivot as the new min, and the new
                                                            // pivot
        }

        return pivot; //unsure why I need this
    }

}

另外,为什么我需要最后一行返回枢轴?我正在使用 eclipse,它说该方法必须返回一种 int,但它不是已经这样做了吗?我想知道这是否是我的问题。

【问题讨论】:

    标签: java sorting binary-search


    【解决方案1】:

    这一行

    findPivot(arr, pivot, min, pivot / 2); // return the arr, the pivot as the new max, and the new pivot
    

    不返回任何内容。您只是忘记添加 return 关键字。 (还有 2 行之后你也会忘记它)。添加两个返回,您返回枢轴的最后一行可以省略。

    【讨论】:

      【解决方案2】:

      我尝试编辑 @maxemann96 的答案,但“建议的编辑队列已满”。

      换句话说,maxemann96 想说的是你完全忽略了搜索结果。

      您可以尝试将您的 findPivot 方法替换为以下内容:

          // feeding in arr, max, min, and pivot point
          static int findPivot(int[] arr, int max, int min, int pivot) {
          
              // base case
              if (max - min < 1) {
                  return pivot;
              }
      
              // binary search
              if (arr[pivot] < arr[max]) {
                   // return the arr, the pivot as the new max, and the new pivot
                  return findPivot(arr, pivot, min, pivot / 2);
              }
              
              // return the arr, the pivot as the new min, and the new pivot
              return findPivot(arr, max, pivot, max - (pivot / 2));
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-21
        • 1970-01-01
        • 2018-06-24
        • 2015-09-29
        • 2018-07-08
        • 1970-01-01
        • 2015-04-06
        相关资源
        最近更新 更多