Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static int binarySearch(String[] A, int left, int right, String V) {
- int middle;
- if (left > right) {
- return -1;
- }
- middle = (left + right) / 2;
- int compare = V.compareTo(A[middle]);
- if (compare == 0) {
- return middle;
- }
- if (compare < 0) {
- return binarySearch(A, left, middle - 1, V);
- } else {
- return binarySearch(A, middle + 1, right, V);
- }
- }
- static public String sortedLinearSearch(String[] A, String B) {
- for (int k = 0; k < A.length; k += 2) {
- int compare = A[k].compareTo(B);
- if (compare == 0) {
- return A[k + 1];
- }
- }
- return "The book was not found.";
- }
- private void searchActionPerformed(java.awt.event.ActionEvent evt) {
- ArrayList<String> books = new ArrayList<String>();
- BufferedReader br = null;
- try {
- br = new BufferedReader(new FileReader("BookList.txt"));
- String title;
- while ((title = br.readLine()) != null) {
- books.add(title);
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- br.close();
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- String[] bookList = new String[books.size()];
- books.toArray(bookList);
- String[] bookName = new String[books.size() / 2];
- String[] bookNum = new String[books.size() / 2];
- for (int i = 0; i <= books.size() / 2 - 1; i++) {
- bookName[i] = bookList[2 * i + 1];
- bookNum[i] = bookList[2 * i];
- test.append(bookNum[i]);
- test.append(bookName[i] + "\n");
- }
- linearOut.setText(sortedLinearSearch(bookList, refIn.getText()));
- if (binarySearch(bookNum, 0, books.size() / 2 - 1, refIn.getText()) < 0) {
- binaryOut.setText("The boox was not found.");
- } else {
- binaryOut.setText(bookName[binarySearch(bookNum, 0, books.size() / 2 - 1, refIn.getText())]);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement