2016-06-04 7 views
0

NetBeans를 사용하여 참조 번호가있는 일종의 라이브러리 데이터베이스를 프로그래밍하여 책을 찾습니다. 참조 번호가 라이브러리에 있는지 확인하기 위해 선형 및 이진 검색을 모두 사용하지만 이진 검색은 참이어야 할 때 false를 반환합니다. 이진 검색 할 때 false를 반환하는 이유이진 검색은 반환 값이 true 일 때 false를 반환합니다.

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

} 

난 그냥 이해가 안 :이 부분에 내가하는 데 문제가 프로그램의

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

} 

} 

부품 : 이것은 내 전체 코드처럼 보이는 것입니다 그것은 진실입니다. 선형 검색조차도 사실 일 때 참을 리턴합니다.

답변

0

선형 검색과 이진 검색에 동일한 배열을 사용하고 있습니다.
이전에 배열을 정렬하는 것을 잊었습니까?

바이너리 검색을 가능하게하는 것은 주어진 배열이 정렬된다는 사실입니다. 값은 한 방향으로 만 이동합니다 (대부분 커짐).
코드에서 어떤 종류의 정렬도 보이지 않습니다. 바이너리 검색이 작동하는 가장 중요한 조건은 정렬 된 배열입니다. 생각해 보면 다음과 같습니다. 배열이 두 부분으로 "잘라내어지고"(한 부분이 중간보다 크고 다른 부분이 더 작은 정렬 된 배열과 달리 각 부분을 정의하지 않고 *), 주어진 값과 발견 된 값이 같지 않을 때마다
배열이 정렬되지 않았기 때문에 올바른 값을 얻을 확률이 매우 낮기 때문에 검색시 "가리키는"값을 기준으로 원하는 값을 찾을 방법이 없습니다
바램 가치가 중간에 있었거나 "경로"가 걸리면 어떻게 될지 모릅니다 (자주 발생하지는 않을 것입니다).

*도 같을 수 있습니다. 그냥 아이디어를주고.

+0

멍청한 질문 인 경우 확실하지 않지만 어떻게 구성 하시겠습니까? 현재 텍스트 파일은 한 줄에 참조 번호와 함께 쓰여지고 다음 줄에 책 제목 등이 쓰여지는 식으로 계속됩니다. 예 : 톰 소여의 모험 허클베리 핀 – spencerbro12

+0

잘, 당신은 당신의 referrnce 번호가 라이브러리에있는 경우 toknow하지 않습니다 싶어? 참조 번호를 정렬 할 수 있습니다. 검색을 실행합니다. 당신은 어떤 종류 든 사용할 수 있습니다. 가장 쉬운 것은 거품 정렬 일 것이지만 그가 느리다는 것을 명심하십시오 (O (n^2)). 당신은 또한 merge sort를 사용할 수 있습니다, 그는 더 빠릅니다 (n * log (n)) 그리고 이진 검색에 대한 글쓰기에서의 similer의 종류입니다. – Amirag

+0

나는 이러한 정렬 방법에 대해 아직 배워 보지 못했습니다. – spencerbro12