【发布时间】:2019-06-19 22:14:32
【问题描述】:
当数组中存在搜索值(SV)时显示输出。但如果它不存在则不会。它不断要求输入并不断循环。
这是我第一次尝试为二进制搜索编写代码
import java.util.Scanner;
public class Binary_search {
public static void main() {
Scanner input = new Scanner(System.in);
int start = 0;
int end = arr.length;
//I used flag to end the loop
int Flag = 0;
int mid = 0;
int SV = input.nextInt();
//here I enter values in the array
for (int x = 0; x <= 4; x++) {
arr[x] = input.nextInt();
}
//here I start a loop for the search
while (Flag == 0) {
mid = (start + end) / 2;
if (mid == SV) {
System.out.println("Number Found" + arr[mid]);
Flag = Flag + 1;
} else if (mid > SV) {
end = mid - 1;
} else if (mid < SV) {
start = mid + 1;
}
//this was the second possibility if the number was not present
else if (start == end) {
Flag = Flag + 1;
System.out.println("Number not found");
}
}
}
}
如果 SV 存在于数组中,它将显示它的位置,“找到的数字”+ arr[mid]。但如果它不存在,它应该输出“找不到号码”,但是,这不会发生,它会一直要求输入。
【问题讨论】:
-
你用的是什么输入法?请阅读minimal reproducible example 并相应地增强您的问题。您的代码也缺少设置该数组的方式。请注意,Java 中的变量名采用驼峰式,类名采用大写,其中没有 _!
-
我提醒你,为了使二分搜索起作用,被搜索的数组必须是排序的。
标签: java arrays binary-search bluej