0

这只是您的平均二进制搜索,在我的程序中,我使用这种搜索方法允许用户查找书名。

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"));
    }
}
4

0 回答 0