java - 为什么此二进制搜索代码在 Eclipse IDE 上给出错误的输出?

标签 java eclipse binary-search

为什么此二分搜索代码在 Eclipse IDE 上给出错误的输出,但在提交到 Coursera 时却被接受?这是一个示例输入,它显示了错误的输出。

示例输入:
5 3 2 4 1 5
3 1 2 7

输出:
-1 -1 -1

显然,存在的元素“1”是输入数组。但其输出是 -1 而不是 3。

import java.io.*;
import java.util.*;

public class BinarySearch {

    static int binarySearch(int[] a,int l,int r,int x) {
        //write your code here
    if(l<=r){
    int mid =l + (r - l)/2;
    if(x==a[mid])
        return mid;
    else if(x<a[mid]){
        return binarySearch(a,l,mid-1,x);
    }
    else
        return binarySearch(a,mid+1,r,x);
    }
        return -1;
    }

    public static void main(String[] args) {
        FastScanner scanner = new FastScanner(System.in);
        int n = scanner.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = scanner.nextInt();
        }
        int m = scanner.nextInt();
        int[] b = new int[m];
        for (int i = 0; i < m; i++) {
          b[i] = scanner.nextInt();
        }
        for (int i = 0; i < m; i++) {
            //replace with the call to binarySearch when implemented
            System.out.print(binarySearch(a,0,n-1,b[i]) + " ");
        }
    }
    static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        FastScanner(InputStream stream) {
            try {
                br = new BufferedReader(new InputStreamReader(stream));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }
    }
}

最佳答案

实际上,问题出在您的输入数据上,而不是代码本身。如果您搜索有关二分搜索的信息,您可以找到:“二分搜索是一种搜索算法,用于在排序数组中查找目标值的位置”。您的输入未排序。

在运行搜索之前,您必须对数组进行排序,这将是一个坏主意 - 使用其他算法进行搜索比排序花费的时间更少。

如果您尝试输入排序数据,例如:

5 1 2 3 4 5 
3 1 2 7

结果将是 0 1 -1 - 正如预期的那样。

关于java - 为什么此二进制搜索代码在 Eclipse IDE 上给出错误的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61727328/

相关文章:

java - 在 maven 版本上更新 README 中包含的版本

java - 无法使用 java jackson java 更新 json 文件

java - jackson JsonMappingException : Unrecognized column 'C' : known columns {"A" ,"B"}

java - 为什么 jar 不能在命令行下运行?

eclipse - InconsistenProjectHierarchyException

c++ - 具有三向比较谓词的 STL 函数

f# - f# 中的迭代二分搜索实现

c# - 为什么基本身份验证无法与我的 Java SOAP Web 服务 WCF 客户端一起使用?

eclipse - 减少 Eclipse 的磁盘空间消耗

c# - 在文本框中转换数字的问题