java - 我对查看整数是否在数组中的二进制搜索一直在循环,有人知道为什么吗?(在 Java 中)
问题描述
我用于查看整数是否在数组中的二进制搜索一直在循环,有谁知道为什么会发生这种情况?顺便说一句,我是第一次使用二进制搜索。
我的 Java 代码在这里:
import java.util.Scanner;
public class testBeforeLearning {
private int[] array;
private int target;
public testBeforeLearning(int[] array, int target){
this.array = array;
}
private int low;
private int high;
private int mid;
public Boolean actualSearch(){
low = 0;
high = array.length - 1;
while (target != array[mid]){
mid = (low + high)/2;
if (target == array[mid]){
return true;
}
else if(target > array[mid]){
low = mid + 1;
}
else if (target < array[mid]){
high = mid - 1;
}
}
return false;
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] dataSet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
System.out.println("Please input a number you want to search for in the array:\n");
int target = input.nextInt();
testBeforeLearning binarySearch = new testBeforeLearning(dataSet, target);
System.out.println(binarySearch.actualSearch());
}
}
出于某种原因,我的下限和上限似乎没有增加或减少,我不知道为什么,有人知道为什么吗?
谢谢!
解决方案
您已将 while 条件设置为 target != array[mid]。但是由于目标未初始化(默认为 0)并且数组中不存在 0,因此它将永远存在。您必须在 testBeforeLearning 中设置目标的值。附带说明一下,您可能还应该使 while 条件低 <= 高。
推荐阅读
- php - PHP循环数组直到索引改变
- entity-framework - 实体框架,没有tt文件但想更改ICollection
- python - 如何重写文本文件中的一行?蟒蛇 3.7
- python - 如何将全局变量与类变量进行比较并打印其值
- java - 为什么弹簧靴找不到我的豆子?
- android - 运行时错误:在 Object.callbackFromNative (cordova.js:293) 中找不到类
- hyperledger-fabric - 如何在生产环境中设置 HyperLedger Fabric
- javascript - VSCode 无法识别
元素 - apache-spark - 如何在 Spark SQL 中使用分区发现
- javascript - 引导表从选定行获取数据