我正在尝试在 Java 中实作递回二进制搜索算法。
我正在有序的字符串阵列中寻找一个字符串。
为什么我得到 ArrayIndexOutOfBoundsException 输入“eeeeee”,而不是“eeeeee”?
先感谢您。
import java.util.Scanner;
class binarySearch{
public static boolean recursiveBinarySearch(String[] arr, String searchTerm, int start, int end){
int middle = start (end-start)/2;
if(start > end){
return false;
}
if(arr[middle].equals(searchTerm)){
return true;
} else if(arr[middle].compareTo(searchTerm) > 0){
return recursiveBinarySearch(arr, searchTerm, start, middle-1);
} else if(arr[middle].compareTo(searchTerm) < 0){
return recursiveBinarySearch(arr, searchTerm, middle 1, end);
}
return false;
}
public static void main(String[] args){
Scanner console = new Scanner(System.in);
String[] saved = {"aaaa","bbbb","cccc","ddddd","eeeee"};
String searchTerm = "";
do{
System.out.println("Term to search in the ordered array:");
searchTerm = console.nextLine();
} while(searchTerm.equals(""));
console.close();
if(recursiveBinarySearch(saved, searchTerm, 0, saved.length)){
System.out.println("Term found!");
} else {
System.out.println("Term NOT found!");
}
}
}
uj5u.com热心网友回复:
你end
以saved.length
. 这里的问题是,.length
它将为您提供从 开始计数的长度1
,而阵列与0
.
只需saved.length-1
像in一样end
输入recursiveBinarySearch
,就可以了!
import java.util.Scanner;
class binarySearch{
public static boolean recursiveBinarySearch(String[] arr, String searchTerm, int start, int end){
int middle = start (end-start)/2;
if(start > end){
return false;
}
if(arr[middle].equals(searchTerm)){
return true;
} else if(arr[middle].compareTo(searchTerm) > 0){
return recursiveBinarySearch(arr, searchTerm, start, middle-1);
} else if(arr[middle].compareTo(searchTerm) < 0){
return recursiveBinarySearch(arr, searchTerm, middle 1, end);
}
return false;
}
public static void main(String[] args){
Scanner console = new Scanner(System.in);
String[] saved = {"aaaa","bbbb","cccc","ddddd","eeeee"};
String searchTerm = "";
do{
System.out.println("Term to search in the ordered array:");
searchTerm = console.nextLine();
} while(searchTerm.equals(""));
console.close();
if(recursiveBinarySearch(saved, searchTerm, 0, saved.length-1)){
System.out.println("Term found!");
} else {
System.out.println("Term NOT found!");
}
}
}
uj5u.com热心网友回复:
阵列索引从 0 到 4,您将其传递给 save.length,它的值为 5。它不会因“eeeee”而失败,因为代码在到达错误之前找到了阵列中的项目。将行更改为 saved.length-1。
0 评论