gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:49:11 27 4
gpt4 key购买 nike

为什么此二分搜索代码在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com