java - Finding information stored in array by binary search -
this small library 2 books sake of question, allows user type in random number, , if number matches book title of book outputted. i've created class called 'book' houses titles.
string book1, book2;
class book { book (int _input, string book_1, string book_2) { book1 = book_1 = "read book"; book2 = book_2 = "how read book";
i apologize if code 1 big mess makes no sense...
} } arraylist <book> titles = new arraylist <book>(50); public static boolean binarysearch(string [] a, int left, int right, string v) { //binary search int middle; boolean found = false; while (found == false && left <= right) { //if middle item == 0, returns true middle = (left + right)/2; int compare = a[middle].compareto(v); if (compare == 0) { found = true; } else { if (compare >0) { right = middle -1; } else { left = middle + 1; } } } if (left > right) { return false; } else { return true; } }
then problem...i'm not sure how use binary search output information after pressing "find" button, ideas on should below make work?
private void findbuttonactionperformed(java.awt.event.actionevent evt) { //take inputted values match book title int input = integer.parseint(enternumberfield.gettext()); //store values in array book c = new book (input, book1, book2); titles.add(c); string temp; //calls out information in array (int j=0; j<=input; j++) { (int x=0; x<=input; x++) { temp = titles.get(x) + "\n"; } binarysearchfield.settext("" + j); //should output book title }
you want binary search return not true or false. want return book
, item found, or null
if found no book matching query. consistent want change name binarysearch, getbook, or other better suited name. in case don't want know if element there, want element use later (printing).
this how collections expected behave when query them. check out methods of java collections , see same, returning item if it's there, or null.
here example code. example code! modify like, , careful bugs, used search i'm going assume correct start with. know there better many ways of storing key value, map example, i'm not going use here.
public class book{ public string title; public int sametitle(string booktitle) { return this.title.compareto(booktitle); } } public static book getbook(book [] a, int left, int right, string booktitle) { //binary search int middle; while (left <= right) { //if middle item == 0, returns true middle = (left + right)/2; int compare = a[middle].sametitle(booktitle); if (compare == 0) { return a[middle]; } else { if (compare >0) { right = middle -1; } else { left = middle + 1; } } } return null; } // example use of getting , using book book b = getbook(...); if (b != null){ system.out.println("success! found book " + b); }
Comments
Post a Comment