java - 在java中对整数数组进行二进制搜索

标签 java arrays algorithm binary-search

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

首先出现以下编译错误,为什么??

This method must return a result of type 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);
}

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

最佳答案

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

您的算法与引用的算法的不同之处在于您的算法在每次“拆分”时构造一个新数组。因此,我们可以说它是相对低效的,因为您使用了太多内存而实际上并不需要它。

关于java - 在java中对整数数组进行二进制搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28099177/

相关文章:

c - 冒泡排序,使所有以数字 5 结尾的数字按升序排列

java - Android:无法读取用户使用 URI 中的 getString() 和 getPath() 选择的 PDF 文件

Java:使用等于覆盖从列表中删除对象

Java 字符串值与子字符串后的文本不匹配

javascript - 使用 JavaScript 数组在字符串中添加两个字母的百分比

html - 如何在 C 中查找所有出现的子字符串

string - 什么是最适合用于比较电视节目标题的字符串距离算法?

java - 使用 Apache Commons Configuration 2.5 从 xml 文件读取 map 的最优雅的方法是什么?

java - 带有按钮和复选框的 Jpanel 数组

C++ 二进制搜索函数不打印