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

为什么此二进制搜索代码在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());
        }
    }
}
评论