【发布时间】:2020-06-09 09:58:47
【问题描述】:
我有以下二进制搜索方法和以下驱动程序代码。我在输出中搜索显示的两个值都存在于数组中。
搜索方法
//Method for binary search. This method will also cut our array
public static int binarySearch(int[] nums, int x) {
//Bounds
int l = 0, r = nums.length - 1;
//While the size of the array is not 1
while (l <= r) {
//Middle element
int m = l + (r - 1) / 2;
//If our element is the middle
if (nums[m] == x) return m;
//If x is greater, cut to right half
else if (x > nums[m]) l = m + 1;
//Else, ignore right half
else r = m - 1;
}
//If we didn't find the element
return -1;
}
驱动代码和输出
public class searcher {
public static void main(String[] args) {
/* Initialize a new scanner for user input, initialize random for the
computer to pick a number */
Scanner s = new Scanner(System.in);
//Variable for user input
int guess;
//Do-while loop
do {
System.out.println("Enter a number to search for (0 to quit): ");
//Get the user's guess
guess = s.nextInt();
//Search for the guess in the array of numbers
int i = binarySearch(nums, guess);
System.out.println(i);
//If the number is not found
if (i == -1) {
System.out.println("Your number does not occur in this list.");
}
//If it is
else {
System.out.println("Your number occurs at position " + i);
}
} while (guess != 0);
}
}
/*
Output
Enter a number to search for (0 to quit):
1
1
Your number occurs at position 1
Enter a number to search for (0 to quit):
90
<------- Program doesn't stop running from here...? */
如果找到输入的数字的索引,我希望得到一个输出,如果没有,该方法应该返回 -1,以便我可以打印未找到
【问题讨论】:
-
您确定
num数组已排序? -
@ b.m是的,它是指的,但我应该自己重新排序吗? span>
-
提示:
m = l + (r - 1) / 2并不代表你认为的那样。为三个变量的值添加一些日志记录,您就会发现问题。 -
(我们可以根据“未命名为变量”@“。) span>
-
尝试调试看看出了什么问题。 (例如记录间隔边界)
标签: java arrays algorithm binary-search