【问题标题】:binary search on array of integer in javajava中整数数组的二进制搜索
【发布时间】:2015-03-21 20:36:51
【问题描述】:

我知道这是一个非常有名的问题,并且已经提供了很多答案,但我正在尝试在我自己的 java 中实现二进制搜索算法。

首先得到以下编译错误,为什么?

这个方法必须返回一个int类型的结果

第二种方法与this famous solution的不同之处

public static int binarySearch(int test[], int num){

    int midLength = test.length/2;
    int fullLength = test.length;

    if(num > test[midLength]){
        int newArray[] = new int[fullLength - midLength];
        for (int j = 0; j<= midLength ; j++){
            newArray[j] = test[midLength + j];

        }
        return binarySearch(newArray, num);
    }
    else if(num < test[midLength]){
        int newArray[] = new int[midLength];
        for (int j = 0; j<= fullLength - midLength ; j++){
            newArray[j] = test[j];

        }
        return binarySearch(newArray, num);
    }
    else if(num == test[midLength]){
        return test[midLength];
    }

}

public static void main(String[] args) {
    int test[] = {2,8,1,6,4,6};
    Arrays.sort(test);
    int num = ArraysTest.binarySearch(test, 1);
    System.out.println(num);
}

请忽略边界条件和逻辑错误,因为这是草稿版本。

【问题讨论】:

    标签: java arrays algorithm binary-search


    【解决方案1】:

    binarySearch 函数末尾缺少一个 return。在 Java 中,编译器验证在每个可能的执行路径上是否存在正确类型的返回。在您的情况下,如果所有测试都是错误的,那么执行会在没有 returned 值的函数结束时上升,这违反了函数合同。

    您的算法与引用的算法不同之处在于您的算法在每个“拆分”处构造一个新数组。因此,我们可以说它的效率相对较低,因为您使用了太多的内存而没有任何真正的需要。

    【讨论】:

      【解决方案2】:

      binarySearch() 方法中没有“else”子句。可以通过在方法末尾添加 return 语句来完成这种失败的情况。换句话说,“else”不需要是明确的。编译器认为有可能没有任何测试(if 和 else-ifs)将通过,因此该方法不返回任何内容。此外,由于该方法是递归的,它必须有一个默认(转义)子句。否则,它将永远调用自己。因此,只需删除 return test[midLength]; 周围的 else-if。

      【讨论】:

        【解决方案3】:

        Jean 是对的,你没有在函数的最后一个返回任何值,那么如果没有任何 if 条件和 else-if 条件成立怎么办。

        第二件事,当你使用 else-if 时,你必须在最后提供 else 条件,这样代码才不会失败。

            int midLength = test.length/2;
            int fullLength = test.length;
        
            if(num > test[midLength]){
                int newArray[] = new int[fullLength - midLength];
                for (int j = 0; j<= midLength ; j++){
                    newArray[j] = test[midLength + j];
        
                }
                return binarySearch(newArray, num);
            }
            else if(num < test[midLength]){
                int newArray[] = new int[midLength];
                for (int j = 0; j<= fullLength - midLength ; j++){
                    newArray[j] = test[j];
        
                }
                return binarySearch(newArray, num);
            }
            else if(num == test[midLength]){
                return test[midLength];
            }
        
            //if it is not matched with any conditions above.
            else{
                return 0;
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-25
          • 2012-01-04
          • 1970-01-01
          • 2017-04-07
          • 1970-01-01
          相关资源
          最近更新 更多