【发布时间】:2015-07-13 22:53:33
【问题描述】:
我有一个通用的二进制搜索,它似乎与Integers 一起运行良好。但是,当我尝试将它与Strings 一起使用时,它有时会崩溃,并在各个行显示ArrayIndexOutOfBoundsException;特别是我多次使用同一个字母指定一个单词的键。例如String key = "peach"; 返回正确的索引,String key = "blueberry"; 未找到,String key = "scoop"; 导致失败。它似乎与T 中的(key.equals(list[mid])) 有关,但我无法理解。感谢您的帮助。
public class BinarySearch {
private BinarySearch() { }
private static <T extends Comparable<? super T>> int search(T[] list, int first, int last, T key){
int foundPosition;
int mid = first + (last - first) / 2;
if (first > last)
foundPosition = -1;
else if (key.equals(list[mid]))
foundPosition = mid;
else if (key.compareTo(list[mid]) < 0)
foundPosition = search(list, first, mid - 1, key);
else
foundPosition = search(list, mid + 1, last, key);
return foundPosition;
}
public static void main(String args[]) {
Integer [] a = {0,2,4,6,8,10,12,14,16};
int finalIndex = 9;
System.out.println("Integer test array contains...");
for (Integer a1 : a) {
System.out.print(a1 + " ");
}
int result;
for (int key = -4; key < 11; key++) {
result = BinarySearch.search(a, 0, finalIndex, key);
if (result < 0)
System.out.println("\n" + key + " is not in the array.");
else
System.out.println("\n" + key + " is at index " + result + ".");
}
String[] searchFruits = {"lemon", "apple", "banana", "peach", "pineapple", "grapes", "blueberry", "papaya"};
System.out.println("\nChecking fruits...");
System.out.println("String test array contains...");
for (String a1 : searchFruits) {
System.out.print(a1 + " ");
}
int fruit = 8;
int fresult;
String key = "blueberry";
fresult = BinarySearch.search(searchFruits, 0, fruit, key);
if (fresult < 0)
System.out.println("\n" + key + " is not in the array.");
else
System.out.println("\n" + key + " is at index " + fresult + ".");
}
}
【问题讨论】:
-
仅供参考,您始终可以使用调试器单步执行代码以查看发生了什么。
标签: java arrays generics binary-search compareto