我查看数组中是否有整数的二进制搜索永远循环,有人知道为什么吗? (在 Java 中)
My binary search for seeing if an integer is in an array is looping forever, does anyone know why? (in 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]。但由于 target 未初始化(默认为 0)且 0 不存在于数组中,因此它将永远持续下去。
你必须在 testBeforeLearning 中设置 target 的值。在旁注中,您可能还应该将 while 条件设置为 low <= high.
我的二进制搜索是为了查看一个整数是否在数组中而永远循环,有人知道为什么会发生这种情况吗?对了,我是第一次使用二分查找
我的 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]。但由于 target 未初始化(默认为 0)且 0 不存在于数组中,因此它将永远持续下去。 你必须在 testBeforeLearning 中设置 target 的值。在旁注中,您可能还应该将 while 条件设置为 low <= high.