当返回值应该为 true 时,二分查找一直返回 false

Posted

技术标签:

【中文标题】当返回值应该为 true 时,二分查找一直返回 false【英文标题】:Binary Search keeps returning false when the return value should be true 【发布时间】:2016-06-04 21:40:47 【问题描述】:

我正在使用 NetBeans 编写一种带有参考编号的图书馆数据库来查找书籍。我同时使用线性搜索和二进制搜索来确定参考号是否在库中,但是当它应该为真时,二进制搜索会一直返回假。这是我的整体代码的样子:

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);
     


我只是不明白为什么二进制搜索在应该为真时返回假。即使是线性搜索,当它为真时也会返回真。

【问题讨论】:

【参考方案1】:

我发现您在线性搜索和二分搜索中都使用了相同的数组。 之前是不是忘记给数组排序了?

使二分搜索成为可能的原因是给定数组已排序 - 值仅以一种方式排列(大多数情况下变得更大)。 我在您的代码中看不到任何类型的排序 - 二进制搜索工作的最重要条件是排序数组。 如果你仔细想想,会发生什么: 每次给定值和找到的值不相等时,数组都被“切割”成 2 部分(没有任何定义每个部分的东西,不像排序数组,其中一部分大于中间,另一部分更小*) . 因为数组没有排序,得到正确值的机会很小,搜索没有办法根据他“指向”的值找到你想要的值 如果希望的值在中间,或者如果它采用的“路线”会以某种方式导致它(不太可能经常发生),那么您的代码就会起作用。

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

【讨论】:

不确定这是不是一个愚蠢的问题,但是您将如何组织它?因为目前文本文件的一行是参考号,然后是下一行的书名,依此类推。示例:1 汤姆索亚历险记 2 哈克贝利费恩 好吧,你想知道引用号码是否在图书馆里,不是吗?您可以对参考编号进行排序。并对其进行搜索。你可以使用任何种类。最简单的将是冒泡排序,但请记住他很慢(O(n ^ 2))。你也可以使用归并排序,他更快(n*log(n)) 并且在他的二分搜索写作中更相似。 我还没有了解这些排序形式。我们目前正在使用递归 合并排序正在与递归一起使用;) 导师是如何希望你在不排序的情况下测试它的?也许在您手动排序后输入输入?

以上是关于当返回值应该为 true 时,二分查找一直返回 false的主要内容,如果未能解决你的问题,请参考以下文章

查找重复的单词

二分查找

利用python实现二分法

当应该为真时,Android Studio 改造响应返回布尔值为假

PHP数组的二分查找算法

Leetcode No.162 寻找峰值(二分查找)