这只是你的平均二进制搜索,在我的程序中我使用这种搜索方法来允许用户查找书名。
String [] binaryArray = {"4", "6", "10"}; //the chosen binary numbers to look for
public static Boolean binarySearch(String [] A, int left, int right, String V) {
int middle;
Boolean found = false;
while (found == false && left <= right) {
//If middle item == 0, returns true
middle = (left + right)/2;
int compare = A[middle].compareTo(V);
if (compare == 0) {
found = true;
} else {
if (compare >0) {
right = middle -1;
} else {
left = middle + 1;
}
}
}
if (left > right) {
return false;
} else {
return true;
}
}
现在我选择IF语句来输出正确的响应,但想象一下,如果数据库是用于可能有数百万条目的真实库。这显然不会很好。那么在没有IF语句的情况下,我能找到所需响应的方式是什么?任何想法或建议将不胜感激!
private void findBookActionPerformed(java.awt.event.ActionEvent evt) { //finds book...
String input = enterNumberField.getText(); //input number to see if it matches up
if ("4".equals(input)) {
binarySearchField.setText("Book Title" + binarySearch(binaryArray, 0, binaryArray.length-1, "4"));
} else if("6".equals(input)){
binarySearchField.setText("Book Title" + binarySearch(binaryArray, 0, binaryArray.length-1, "6"));
} else if("10".equals(input)){
binarySearchField.setText("Book Title" + binarySearch(binaryArray, 0, binaryArray.length-1, "10"));
}
}