二进制搜索不会停止吗?
来源:爱站网时间:2021-09-16编辑:网友分享
我具有以下二进制搜索方法和以下驱动程序代码。我搜索的两个显示在输出中的值都存在于数组中。搜索方法//用于二进制搜索的方法。 ...
问题描述
我具有以下二进制搜索方法和以下驱动程序代码。我搜索的两个显示在输出中的值都存在于数组中。
搜索方法
//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 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
我期望找到找到的输入数字的索引,如果没有找到,该方法应该返回-1,这样我就可以打印出未找到的数字
思路一:
int m = l + (r - 1) / 2; // this is not correct, you are subtracting "1"
您需要减去“ left”(为清楚起见,对变量名进行了编辑):
int mid = left + (right - left) / 2;
或者更好一点:
int mid = (left+ right) >>> 1;
思路二:
您减去1两次。
r = nums.length - 1;
然后
int m = l + (r - 1) / 2;
应该是
int m = l + (r - l) / 2;