我想实现二进制搜索,但外部提供搜索键。这意味着我的硬盘中有一个文件。我想从这个文件中读取键值。我为此目的写下了一段代码。但是代码无限循环。
这是我的代码:
public class T5 {
public static void main(String args[])throws Exception{
double arr[]= new double[]{86.0,12.0,55.0,90.0,77.0,22.0,25.0,33.0,45.0,20.0,23.0};
int first=0;
int last=(arr.length)-1;
Scanner x= new Scanner(new File("D:\\Test_1.txt"));
while(x.hasNext()){
double a =x.nextDouble();
while(first<=last){
int mid=(first+last)/2;
if(arr[mid]==a){
System.out.println("Search successful");
}
if(arr[mid]<a){
last=mid+1;
}
else{
last=mid-1;
}
}
}
}
}
我在这里提到的Text_1.txt文件就像那样
86.0
25.0
30.0
18.0
90.0
88.0
70.0
87.0
55.0
此处提到的数组arr []是与键值进行比较的值。 arr []由86.0组成,文件有86.0,因此搜索成功。该文件有25.0,arr的值也是25.0。所以再次搜索成功。该文件的值为30.0,但arr []没有。所以搜索不成功。
这是概念,但为什么它会进入无限循环。任何建议和讨论都是最受欢迎的。
答案 0 :(得分:2)
首先,应该对二进制搜索应用的数组进行排序!
您应该始终尝试可视化您的算法。对于二进制搜索,你必须想象左边有2个边界,左边界限向左移动,右边界移动到左边,进程一直持续到它们发生碰撞,或直到找到你的元素。
我很明显你甚至没有试图追踪你的算法...
另外,请注意在另一个内部有一个while循环。而且你永远不会在第一个循环开始时重置你的第一个和最后一个变量。这是错误的。
最后一件事,更喜欢first + (last - first) / 2
到(last + first) / 2
。因为(last + first) / 2
可能会溢出,而first + (last - first) / 2
可能会溢出。
让我们将您的程序分解为2个函数,一个将执行二进制搜索,另一个将读取。
1)
static boolean binarySearch(double a) {
double[] arr = {1, 2, 3, 4, 5, 6};
Arrays.sort(arr);
int first = 0;
int last = arr.length - 1;
while (first <= last) {
int mid = first + (last - first) / 2;
if (arr[mid] == a) {
return true;
} else if (arr[mid] < a) {
first = mid + 1;
} else /*if (arr[mid] > a)*/{
last = mid - 1;
}
}
return false;
}
2)
public static void main(String... args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
double d = sc.nextDouble();
binarySearch(d);
}
}
此外,JDK中还有一个binarySearch方法,因此您的代码变为:
public static void main(String... args) {
Scanner sc = new Scanner(System.in);
double[] arr = {1, 2, 3, 4, 5, 6};
Arrays.sort(arr);
while (sc.hasNext()) {
double d = sc.nextDouble();
Arrays.binarySearch(arr, d);
}
}