为什么此二进制搜索代码在Eclipse IDE上给出错误的输出,但是在提交给Coursera时被接受?这是一个示例输入,显示错误的输出。
样本输入:5 3 2 4 1 53 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());
}
}
}
实际上,问题出在您的输入数据,而不是代码本身。如果搜索有关二进制搜索的信息,则可以找到:“二进制搜索是一种在sorted数组中查找目标值位置的搜索算法”。您的输入未排序。
您必须在运行搜索之前对数组进行排序,这将是一个糟糕的主意-使用其他算法进行搜索将比排序花费更少的时间。
如果您尝试输入排序的数据,例如:
5 1 2 3 4 5
3 1 2 7
结果将为0 1 -1
-符合预期。