繁体   English   中英

当返回值应为true时,二进制搜索将始终返回false

[英]Binary Search keeps returning false when the return value should be true

我正在使用NetBeans对带有参考号的图书馆数据库进行编程,以查找书籍。 我同时使用线性和二进制搜索来确定参考号是否在库中,但是二进制搜索在应为true时始终返回false。 这是我的总体代码:

package u3a3_bookslist;

import java.util.*;
import java.io.*;

public class bookslist {

//Define the default variables to use in all other methods of the program
public static int index, numSearches;

public static void main(String[] args) {

    //Define the ArrayList to store the values of 'BookList.txt'
    ArrayList <String> books = new ArrayList <String>();

    //Define the default values to use later in the code
    BufferedReader br = null;
    String referenceNumber;

    //Use a try statement to analyze the entire 'BookList.txt' file and add
    //each value on a new line into the arrayList 'books'
    try {
        br = new BufferedReader(new FileReader("BookList.txt"));
        String word;
        while ((word = br.readLine()) != null ){
            books.add(word);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    //Create a new Array called 'bookList' to store and convert all the values
    //from the 'books' arrayList
    String [] bookList = new String[books.size()];
    books.toArray(bookList);

    //Create a scanner input to ask the user to enter a reference number
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the reference number of a book to determine"
            + " if it is in the library or not: ");

    //Set the variable 'referenceNumber' to whatever value that the user inputted
    //into the Scanner
    referenceNumber = input.next();

    //Obtain the boolean result of either true or false from the Binary and
    //Linear search methods
    Boolean resultLinear = linearSearch(bookList, referenceNumber);
    Boolean resultBinary = binarySearch(bookList, 0, bookList.length-1, referenceNumber);

    //Analyze each element that is contained in the 'bookList' Array
    for (int i = 0; i < bookList.length; i++) {

        //Determine if the value of 'i' is equal to the 'referenceNumber'
        //converted into an int format
        if (i == Integer.parseInt(referenceNumber)) {

            //Determine if the 'i' index of the 'bookList' Array is equal
            //to the user inputted reference number
            if (bookList[i].equals(referenceNumber)) {

                //If the previous statement were true, the 'index' variable
                //was set to equal to current value for 'i'
                index = i;
            }
        }
    }

    //Determine the message to display to the user depending on if the reference
    //number was found in the Array using a Linear Search
    if (resultLinear == true) {
        System.out.println("Linear Search: Reference Number " + referenceNumber +
                " was found in the library. The book with that number is: " + bookList[index+1]);
    } else {
        System.out.println("Linear Search: Reference Number " + referenceNumber
                + " not in the library. No book with that number.");
    }

    //Determine the message to display to the user depending on if the reference
    //number was found in the Array using a Binary search
    if (resultBinary != false) {
        System.out.println("Binary Search: Reference Number " + referenceNumber +
                " was found in the library. The book with that number is: " + bookList[index+1]);
    } else {
        System.out.println("Binary Search: Reference Number " + referenceNumber
                + " not in the library. No book with that number.");
    }


}

//Execute a linear search to determine if the user inputted reference number
//is contained in the bookList Array
static public Boolean linearSearch(String[] A, String B) {
    for (int k = 0; k < A.length; k++) {
        if (A[k].equals(B)) {
            return true;
        }
    }
    return false;
}

//Execute a binary search to determine if the user inputted reference number
//is contained in the bookList Array
public static Boolean binarySearch(String[] A, int left, int right, String V) {

    int middle;
     numSearches ++;
     if (left > right) {
         return false;
     }

     middle = (left + right)/2;
     int compare = V.compareTo(A[middle]);
     if (compare == 0) {
         return true;
     }
     if (compare < 0) {
         return binarySearch(A, left, middle-1, V);
     } else {
         return binarySearch(A, middle + 1, right, V);
     }

}

}

我遇到问题的程序部分如下:

public static Boolean binarySearch(String[] A, int left, int right, String V) {

    int middle;
     numSearches ++;
     if (left > right) {
         return false;
     }

     middle = (left + right)/2;
     int compare = V.compareTo(A[middle]);
     if (compare == 0) {
         return true;
     }
     if (compare < 0) {
         return binarySearch(A, left, middle-1, V);
     } else {
         return binarySearch(A, middle + 1, right, V);
     }

}

我只是不明白为什么二进制搜索应该为True时返回false。 当线性搜索为true时,甚至返回true。

我看到您在线性搜索和二进制搜索中都使用了相同的数组。
您是否忘了对数组进行排序?

使二分查找成为可能的是给定数组已排序的事实-值仅以一种方式进行(大多数情况下会变大)。
我在您的代码中看不到任何排序-二进制搜索起作用的最重要条件是排序数组。 如果您考虑一下,会发生以下情况:每次将数组“切割”为2个部分(没有定义每个部分的任何内容,不像排序的数组,其中一个部分大于中间部分,而另一个则更小*)给定值和发现值不相等。
由于数组未排序,因此获得正确值的机会非常小,搜索无法根据他“指向”的值来找到所需的值
如果希望的值在中间,或者如果它采用的“路线”以某种方式导致了它(很少会经常发生),那么您的代码就会工作。

*也可能相等。 只是给出想法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM