Advertisement
Guest User

Untitled

a guest
May 20th, 2012
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.25 KB | None | 0 0
  1. public static int binarySearch(String[] A, int left, int right, String V) {
  2.         int middle;
  3.         if (left > right) {
  4.             return -1;
  5.         }
  6.         middle = (left + right) / 2;
  7.         int compare = V.compareTo(A[middle]);
  8.         if (compare == 0) {
  9.             return middle;
  10.         }
  11.         if (compare < 0) {
  12.             return binarySearch(A, left, middle - 1, V);
  13.         } else {
  14.             return binarySearch(A, middle + 1, right, V);
  15.         }
  16.     }
  17.  
  18.     static public String sortedLinearSearch(String[] A, String B) {
  19.         for (int k = 0; k < A.length; k += 2) {
  20.             int compare = A[k].compareTo(B);
  21.             if (compare == 0) {
  22.                 return A[k + 1];
  23.             }
  24.         }
  25.         return "The book was not found.";
  26.     }
  27.  
  28.     private void searchActionPerformed(java.awt.event.ActionEvent evt) {                                      
  29.         ArrayList<String> books = new ArrayList<String>();
  30.         BufferedReader br = null;
  31.  
  32.         try {
  33.             br = new BufferedReader(new FileReader("BookList.txt"));
  34.             String title;
  35.             while ((title = br.readLine()) != null) {
  36.                 books.add(title);
  37.             }
  38.         } catch (IOException e) {
  39.             e.printStackTrace();
  40.         } finally {
  41.             try {
  42.                 br.close();
  43.             } catch (IOException ex) {
  44.                 ex.printStackTrace();
  45.             }
  46.         }
  47.         String[] bookList = new String[books.size()];
  48.         books.toArray(bookList);
  49.  
  50.         String[] bookName = new String[books.size() / 2];
  51.         String[] bookNum = new String[books.size() / 2];
  52.  
  53.         for (int i = 0; i <= books.size() / 2 - 1; i++) {
  54.             bookName[i] = bookList[2 * i + 1];
  55.             bookNum[i] = bookList[2 * i];
  56.             test.append(bookNum[i]);
  57.             test.append(bookName[i] + "\n");
  58.         }
  59.  
  60.        
  61.  
  62.         linearOut.setText(sortedLinearSearch(bookList, refIn.getText()));
  63.         if (binarySearch(bookNum, 0, books.size() / 2 - 1, refIn.getText()) < 0) {
  64.             binaryOut.setText("The boox was not found.");
  65.         } else {
  66.             binaryOut.setText(bookName[binarySearch(bookNum, 0, books.size() / 2 - 1, refIn.getText())]);
  67.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement