Java binary search and insert

I'm currently writing a program which is an appointment book. I currently have 4 classes and at the minute it can sort the array and print it out. I'm stuck at binary search and inserting a new appointment record. I will include the classes which i have got.
Appointment
   import java.util.*;
   import java.io.*;
   import java.util.Scanner;
    class Appointment implements Comparable
      private String description;
      private int day;
      private int month;
      private int year;
      private String startTime;
      private String endTime;
      protected static Scanner keyboard = new Scanner(System.in);     
       public Appointment()
         description = "";
         day = 0;
         month = 0;;
         year = 0;;
         startTime = "";
         endTime = "";
       public Appointment(String appDesc, int appDay, int appMonth, int appYear, String appStartTime, String appEndTime)
         description = appDesc;
         day = appDay;
         month = appMonth;
         year = appYear;
         startTime = appStartTime;
         endTime = appEndTime;
       public void display()      
         System.out.print("  Description: " + description);
         System.out.print(", Date: " + day + "/" +month+ "/" +year);
         System.out.println(", Start Time: " + startTime);
         System.out.println(", End Time: " + endTime);
       public void setDay(int day)
      { this.day = day; }
       public int getDay()     
         return day; }
       public void setMonth(int month)
      { this.month = month; }
       public int getMonth()     
         return month; }
       public void setYear(int year)
      { this.year = year; }
       public int getYear()
         return year; }
       public int compareTo(Object obj)
         if (obj instanceof Appointment)
            Appointment appt = (Appointment) obj;
            if (this.day > appt.getDay())
               return 1;
            else if (this.day < appt.getDay());
            return -1;
         return 0;
       public String toString() {
         StringBuffer buffer = new StringBuffer();
         buffer.append("Description: " + description);
         buffer.append(", Date: " + day + "/" +month+ "/" +year);
         buffer.append(", Start Time: " + startTime);
         buffer.append(", End Time: " + endTime);
         return buffer.toString();
       public void read(){
         System.out.print("Description : ");String descIn=keyboard.next();
         System.out.print("Day : ");int dayIn=keyboard.nextInt();
         System.out.print("Month : ");int monthIn=keyboard.nextInt();
         System.out.print("Year : ");int yearIn=keyboard.nextInt();
         System.out.print("Start Time : ");String startIn=keyboard.next();
         System.out.print("End Time : ");String endIn=keyboard.next();
         boolean goodInput = false;
         do{          
            try{
               setDay(dayIn);
               setMonth(monthIn);
               setYear(yearIn);
               goodInput = true;
                catch(IllegalArgumentException e){
                  System.out.println("INVALID ARGUMENT PASSED FOR day or month or year");
                  System.out.println(e);
                  System.out.print("RE-ENTER VALID ARGUMENT FOR DAY : ");dayIn=keyboard.nextInt();
                  System.out.print("RE-ENTER VALID ARGUMENT FOR MONTH : ");monthIn=keyboard.nextInt();
                  System.out.print("RE-ENTER VALID ARGUMENT FOR YEAR : ");yearIn=keyboard.nextInt();                                        
         }while(!goodInput);
   }

Array
import java.util.*;
class Array
     private Appointment[] app;
     private int nElems;
     Appointment tempApp;
     public Array(int max)
          app = new Appointment[max];
          nElems = 0;
     public Array(String desc, int day, int month, int year, String sTime, String eTime)
          app = new Appointment[100];
          nElems = 0;
   public int size()
      { return nElems; }
     void add(){
          Appointment appointmentToAdd = new Appointment();
          // Read its details
          appointmentToAdd.read();
          // And add it to the studentList
          //app[nElems].add(appointmentToAdd);
     public void add(String desc, int day, int month, int year, String sTime, String eTime)
        app[nElems] = new Appointment(desc, day, month, year, sTime, eTime);
        nElems++;             // increment size
          Appointment appointmentToAdd = new Appointment(desc, day, month, year, sTime, eTime);
          // And add it to the studentList
          //app[nElems].add(appointmentToAdd);
      public void insert(Appointment tempApp) {
    int j;
    for (j = 0; j < nElems; j++)
      // find where it goes
      if (app[j] > tempApp) // (linear search)
        break;
    for (int k = nElems; k > j; k--)
      // move bigger ones up
      app[k] = app[k - 1];
    app[j] = tempApp; // insert it
    nElems++; // increment size
   public void display()       // displays array contents
        for(int j=0; j<nElems; j++)    // for each element,
          app[j].display();     // display it
        System.out.println("");
     public void insertionSort()
   int in, out;
   for(out=1; out<nElems; out++) // out is dividing line
     Appointment temp = app[out];    // remove marked person
     in = out;          // start shifting at out
     while(in>0 &&        // until smaller one found,
        app[in-1].getMonth().compareTo(temp.getMonth())>0)
      app[in] = app[in-1];     // shift item to the right
      --in;          // go left one position
     app[in] = temp;        // insert marked item
     } // end for
   } // end insertionSort()
}Menu
import java.util.*;
class Menu{
   private static Scanner keyboard = new Scanner(System.in);
   int option;
     Menu(){
        option=0;
     void display(){
          // Clear the screen
        System.out.println("\n1 Display");
          System.out.println("\n2 Insert");          
          System.out.println("3 Quit");          
     int readOption(){
        System.out.print("Enter Option [1|2|3] : ");
          option=keyboard.nextInt();
          return option;
}Tester
   import java.util.*;
   import java.util.Arrays;
    class ObjectSortApp
       public static void main(String[] args)
               int maxSize = 100;
               Array arr;
               arr = new Array(maxSize)
               Appointment app1 = new Appointment("College Closed", 30, 4, 2009, "09:30", "05:30");;
               Appointment app2 = new Appointment("Assignment Due", 25, 4, 2009, "09:30", "05:30");
         Appointment app3 = new Appointment("College Closed", 17, 4, 2009, "09:30", "05:30");
         Appointment app4 = new Appointment("Easter Break", 9, 4, 2009, "01:30", "05:30");
         Appointment app5 = new Appointment("College Opens", 15, 4, 2009, "09:30", "05:30");
         Appointment app6 = new Appointment("Assignment Due", 12, 4, 2009, "09:30", "05:30");
         Appointment app7 = new Appointment("Exams Begin", 11, 4, 2009, "09:30", "05:30");
            //To sort them we create an array which is passed to the Arrays.sort()
        //method.
        Appointment[] appArray = new Appointment[] {app1, app2, app3, app4, app5, app6, app7};
         System.out.println("Before sorting:");
        //Print out the unsorted array
        for (Appointment app : appArray)
            System.out.println(app.toString()); 
            Arrays.sort(appArray);
         //arr.insertionSort();      // insertion-sort them
         System.out.println("\n\nAfter sorting:");               
        //Print out the sorted array
        for (Appointment app : appArray)
            System.out.println(app.toString());
          Menu appMenu = new Menu();
          int chosenOption;
          do{
             appMenu.display();
               chosenOption=appMenu.readOption();
               for (Appointment app : appArray)
               switch(chosenOption){
                  case 1 : app.display(); break;
                    case 2 : arr.add(); break;
                    default:;
          }while(chosenOption != 3);    
      } // end main()
   } // end class ObjectSortApp

Similar Messages

  • Java Binary Search and sorting in Java

    My program is suppose to search news articles and alphabetize all the words article individually of the text file. Right now the program alphabetizes all the words of the articles including the numbers. The text file will be located below the code. So basically i need to know how to alphabetize every articles words individually.
    //This program reads an input line from the reader put the worda into an array with a count and increases
    //the count each time a word is repeated. It then sorts the words alphabetically in the array and
    //then prints out the array. There are 4 different articles like this one in the text file
    <ID>58</ID>
    <BODY>Assets of money market mutual funds
    increased 720.4 mln dlrs in the week ended yesterday to 236.90
    billion dlrs, the Investment Company Institute said.
        Assets of 91 institutional funds rose 356 mln dlrs to 66.19
    billion dlrs, 198 general purpose funds rose 212.5 mln dlrs to
    62.94 billion dlrs and 92 broker-dealer funds rose 151.9 mln
    dlrs to 107.77 billion dlrs.
    </BODY>
    import java.util.StringTokenizer;
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.FileWriter;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.io.IOException;
    import java.io.FileNotFoundException;
    public class WordsFrequency
       public static void main(String[] args)
          // Initializations
          FileReader reader = null;
          FileWriter writer = null;
          // Open input and output files
          try
              reader = new FileReader("Reuters00.txt");
              writer = new FileWriter("WordsReport.txt");
          catch(FileNotFoundException e)
             System.err.println("Cannot find input file");
             System.exit(1);
          catch(IOException e)
           System.err.println("Cannot open input/output file");
           System.exit(2);
          // Set up to read a line and write a line
          BufferedReader in = new BufferedReader(reader);
          PrintWriter out = new PrintWriter(writer);
          out.println("Copied file is: Words followed by frequency");
          int count = 0;
           wordCount[] wordsArray = new wordCount[100000];
          boolean done = false;
          while(!done)
             String inputLine;
             try
                  inputLine= in.readLine();
             catch(IOException e)
                System.err.println("Problem reading input, program terminates. " );
                inputLine = null;
             if (inputLine == null)
               done = true;
         sortbyWords(wordsArray,count);
               for(int i = 0; i < count;i++)
                out.println(wordsArray.toString());
    else
                   StringTokenizer tokenizer = new StringTokenizer(inputLine);
              while(tokenizer.hasMoreTokens())
                   String token = tokenizer.nextToken();
                        int lengthofString = token.length();
                        char ch = token.charAt(lengthofString-1);
                        if(ch == '.' || ch == ',' || ch == '!' || ch == '?' || ch == ';')
                   token = token.substring(0,lengthofString-1);
    wordCount wordAndCount= new wordCount(token);
                        boolean skip = false;
                        for(int i = 0; i < count; i++)
                        if(token.equalsIgnoreCase(wordsArray[i].getWord()))
                             skip = true;
                             wordsArray[i].increaseFrequency();
                        if(skip == false)
                                  wordsArray[count] = wordAndCount;
                             count++;
    // Close files
    try
    in.close();
    catch(IOException e)
    System.err.println("Error closing file.");
    finally
    out.close();
         public static void sortbyWords(wordCount [] wArray, int size)
         wordCount temp;
         for (int j = 0; j < size-1; j++)
         for (int i = 0; i < size-1; i++)
         if (wArray[i].getWord().compareToIgnoreCase(wArray[i+1].getWord()) > 0)
              temp = wArray[i];
              wArray[i] = wArray[i + 1];
              wArray[i+1] = temp;
    Edited by: IronManNY on Sep 25, 2008 3:24 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    IronManNY wrote:
    My program is suppose to search news articles and alphabetize all the words article individually of the text file. Right now the program alphabetizes all the words of the articles including the numbers. The text file will be located below the code. So basically i need to know how to alphabetize every articles words individually.You want to strip out the numbers?

  • Search and insert from table with RichTextInsertBehavior

    Hi OTN,
    I have a Rich Text Editor which is used to edit CLOB content.
    Near RTE I should have controls to insert special macros with a following scenario:
    I click "Insert Person Link" button - a popup with search through Employees by name appears.
    I choose a person, click OK and a macro like "\[A_PERSON(123)\]" is inserted into RTE field, where 123 is a Metaterm field of selected employee.
    Please, advise me how should I organize this kind of search and insertion? What's the best way, what components should I use?
    Right now I'm using Query with table component.
    But I'm a little stuck with Value field of RichTextEditorInsertBehavior. It should be like "\[A_PERSON(<table.selectedRow.metatermField>)\]"
    How do I choose it? Or is there a totally better way with, say, InputListOfValue component or smth.
    JDev 11.1.1.1.0
    Thanks.
    Edited by: ILya Cyclone on Oct 5, 2009 11:46 PM
    I should have used af:query.

    Hi,
    You can use a traditional exp - imp
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14215/exp_imp.htm
    or new expdp - impdp
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14215/dp_overview.htm#i1009203
    depends on yuor Oracle version.. !!!

  • Difference between Binary search and Linear search

    Dear all,
    If anyone helps me to get the basic difference between binary and Linear search in SAP environment.
    Regards

    Hi,
    In case of linear search system will search from begining.
    that means Example : z table contains single field with values 
    1 2 3 4 5 6 7 8 9 
    if u r searching for a value then system will starts from
    first position. if required value is founded then execution
    will comes out from z table.
    In case of binary search system will starts from mid point.
    if value is not founded then it will search for upper half.
    in  that upper half it will check mid point.like that search
    will takes place.
    Thanks,
    Sridhar

  • How to next consecutive node in binary tree and insert in sql server

    i need to find next node in this tree and insert in sql server ...
    dilip kumar

    It depends you data structure. How do you store this tree structure in the database? What's the database design? BTW, you can see this article which include a related sample :
    Custom Sort in Acyclic Digraph
    T-SQL e-book by TechNet Wiki Community
    My Blog
    My Articles

  • Binary Search and Sequence Search in Archives

    My friends, I need of a example of these alghoritms . Can you help me abouth this?
    thanks

    You are not going to get far in the programming business if you do not know how to search the Internet for information. It's true, it isn't easy if you don't know English well, but that is not going to change. You will not be able to do your work if you constantly have to be asking other people to search the web for you.

  • "Binary search" in READ

    Hi frnds,
      I sumtyms  dont get the desired result while using the
    "BINARY SEARCH" addition with the "READ" statement.
    y is that? is there any rules to be followed to use binary search option in read statement.
    Regards,
    Madan...

    Hi
    Please go thru this.
    Binary Search in Standard Tables
    If you read entries from standard tables using a key other than the default key, you
    can use a binary search instead of the normal linear search. To do this, include the addition
    BINARY SEARCH in the corresponding READ statements.
    READ TABLE <itab> WITH KEY = <f> <result> BINARY SEARCH.
    and
    READ TABLE <itab> WITH KEY <k1> = <f1> ... <kn> = <fn> <result>
    BINARY SEARCH.
    The standard table must be sorted in ascending order by the specified search key. The BINARY
    SEARCH addition means that you can access an entry in a standard table by its key as quickly
    as you would be able to in a sorted table.
    Example
    DATA: BEGIN OF LINE,
    COL1 TYPE I,
    COL2 TYPE I,
    END OF LINE.
    DATA ITAB LIKE STANDARD TABLE OF LINE.
    DO 4 TIMES.
    LINE-COL1 = SY-INDEX.
    LINE-COL2 = SY-INDEX ** 2.
    APPEND LINE TO ITAB.
    ENDDO.
    SORT ITAB BY COL2.
    READ TABLE ITAB WITH KEY COL2 = 16 INTO LINE BINARY SEARCH.
    WRITE: 'SY-SUBRC =', SY-SUBRC.
    The output is:
    SY-SUBRC = 0
    The program fills a standard table with a list of square numbers and sorts them into
    ascending order by field COL2. The READ statement uses a binary search to look
    for and find the line in the table where COL2 has the value 16.
    http://help.sap.com/saphelp_nw2004s/helpdata/en/fc/eb35f8358411d1829f0000e829fbfe/content.htm
    Thanks
    Shiva

  • A little urgent when to use binary search.

    Hi evryone,
    Plz let me know under what kind of conditions can we use binary search addition cause if I use it for every read statement the database acees in se30 goes higher than normal.
    If i randomly select only a few big read table statements the database acees in se30 goes is slightly lesser.
    But I some how dont know where to use binary search and where not to with read statements.
    Expecting an early reply.
    Rgds,
    Anu

    hi,
    If you read entries from standard tables using a key other than the default key, you can use a binary search instead of the normal linear search. To do this, include the addition BINARY SEARCH in the corresponding READ statements.
    READ TABLE <itab> WITH KEY <k1> = <f1>... <kn> = <fn> <result>
                                                           BINARY SEARCH.
    The standard table must be sorted in ascending order by the specified search key. The BINARY SEARCH addition means that you can access an entry in a standard table by its key as quickly as you would be able to in a sorted table.
    REPORT demo_int_tables_read_index_bin.
    DATA: BEGIN OF line,
            col1 TYPE i,
            col2 TYPE i,
          END OF line.
    DATA itab LIKE STANDARD TABLE OF line.
    DO 4 TIMES.
      line-col1 = sy-index.
      line-col2 = sy-index ** 2.
      APPEND line TO itab.
    ENDDO.
    SORT itab BY col2.
    READ TABLE itab WITH KEY col2 = 16 INTO line BINARY SEARCH.
    WRITE: 'SY-SUBRC =', sy-subrc.
    The output is:
    SY-SUBRC =    0
    The program fills a standard table with a list of square numbers and sorts them into ascending order by field COL2. The READ statement uses a binary search to look for and find the line in the table where COL2 has the
    reward if useful.
    Thanks,
    Madhukar

  • When to use binary search ... little urgent.

    Hi evryone,
    Plz let me know under what kind of conditions can we use binary search addition cause if I use it for every read statement the database acees in se30 goes higher than normal.
    If i randomly select only a few big read table statements the database acees in se30 goes is slightly lesser.
    But I some how dont know where to use binary search and where not to with read statements.
    Expecting an early reply.
    Rgds,
    Anu

    Hi,
    If  you read entries from standard tables using a key other than the default key, you can use a binary search instead of the normal linear search. To do this, include the addition BINARY SEARCH in the corresponding READ statements.
    READ TABLE <itab> WITH KEY <k1> = <f1>... <kn> = <fn> BINARY SEARCH.
    The standard table must be sorted in ascending order by the specified search key. The BINARY SEARCH addition means that you can access an entry in a standard table by its key as quickly as you would be able to in a sorted table.
    BINARY SEARCH approaches the middle entry in the table, decides if it matches, or lexically greater than or equal to the key being searched. It accordingly skips either the top or bottom part of the internal table and searches the other half. It repeats this process till it finds the row.
    Using BINARY SEARCH with READ is the most efficient way to read standard internal tables which are sorted by the key used to search them
    BINARY SEARCH addition when reading a sorted table is not required, as it happens by default. It makes a good difference in performance if you are reading a large standard internal table without sorting and reading by BINARY SEARCH.
    Regards,
    Padmam.

  • Multiple file search and replace

    Does anyone know if it is possible to do search / replaces in script, text etc over multiple files?  If not, is there any 3rd party software available to do it?
    I have hundreds of files I have to make the same change in and just wanted to find out before I have to do the mind-numbing process of going through them all.
    Any help will be greatly appreciated!

    Depending upon what type of files and what kind of changes you need to make, sure you can. You can do a google search for 'binary search and replace'; here's one of the first results, which searches for and replaces strings in multiple text and/or binary files:
    http://gnuwin32.sourceforge.net/packages/gsar.htm

  • Binary search tree in java using a 2-d array

    Good day, i have been wrestling with this here question.
    i think it does not get any harder than this. What i have done so far is shown at the bottom.
    We want to use both Binary Search Tree and Single Linked lists data structures to store a text. Chaining
    techniques are used to store the lines of the text in which a word appears. Each node of the binary search
    tree contains four fields :
    (i) Word
    (ii) A pointer pointing to all the lines word appears in
    (iii) A pointer pointing to the subtree(left) containing all the words that appears in the text and are
    predecessors of word in lexicographic order.
    (iv) A pointer pointing to the subtree(right) containing all the words that appears in the text and are
    successors of word in lexicographic order.
    Given the following incomplete Java classes BinSrchTreeWordNode, TreeText, you are asked to complete
    three methods, InsertionBinSrchTree, CreateBinSrchTree and LinesWordInBinSrchTree. For
    simplicity we assume that the text is stored in a 2D array, a row of the array represents a line of the text.
    Each element in the single linked list is represented by a LineNode that contains a field Line which represents a line in which the word appears, a field next which contains the address of a LineNode representing the next line in which the word appears.
    public class TreeText{
    BinSrchTreeWordNode RootText = null;// pointer to the root of the tree
    String TextID; // Text Identification
    TreeText(String tID){TextID = tID;}
    void CreateBinSrchTree (TEXT text){...}
    void LinesWordInBinSrchTree(BinSrchTreeWordNode Node){...}
    public static void main(String[] args)
    TEXT univ = new TEXT(6,4);
    univ.textcont[0][0] = "Ukzn"; univ.textcont[0][1] ="Uct";
    univ.textcont[0][2] ="Wits";univ.textcont[0][3] ="Rhodes";
    univ.textcont[1][0] = "stellenbosch";
    univ.textcont[1][1] ="FreeState";
    univ.textcont[1][2] ="Johannesburg";
    univ.textcont[1][3] = "Pretoria" ;
    univ.textcont[2][0] ="Zululand";univ.textcont[2][1] ="NorthWest";
    univ.textcont[2][2] ="Limpopo";univ.textcont[2][3] ="Wsu";
    univ.textcont[3][0] ="NorthWest";univ.textcont[3][1] ="Limpopo";
    univ.textcont[3][2] ="Uct";univ.textcont[3][3] ="Ukzn";
    univ.textcont[4][0] ="Mit";univ.textcont[4][1] ="Havard";
    univ.textcont[4][2] ="Michigan";univ.textcont[4][3] ="Juissieu";
    univ.textcont[5][0] ="Cut";univ.textcont[5][1] ="Nmmu";
    univ.textcont[5][2] ="ManTech";univ.textcont[5][3] ="Oxford";
    // create a binary search tree (universities)
    // and insert words of text univ in it
    TreeText universities = new TreeText("Universities");
    universities.CreateBinSrchTree(univ);
    // List words Universities trees with their lines of appearance
    System.out.println();
    System.out.println(universities.TextID);
    System.out.println();
    universities.LinesWordInBinSrchTree(universities.RootText);
    public class BinSrchTreeWordNode {
    BinSrchTreeWordNode LeftTree = null; // precedent words
    String word;
    LineNode NextLineNode = null; // next line in
    // which word appears
    BinSrchTreeWordNode RightTree = null; // following words
    BinSrchTreeWordNode(String WordValue)
    {word = WordValue;} // creates a new node
    BinSrchTreeWordNode InsertionBinSrchTree
    (String w, int line, BinSrchTreeWordNode bst)
    public class LineNode{
    int Line; // line in which the word appears
    LineNode next = null;
    public class TEXT{
    int NBRLINES ; // number of lines
    int NBRCOLS; // number of columns
    String [][] textcont; // text content
    TEXT(int nl, int nc){textcont = new String[nl][nc];}
    The method InsertionBinSrchTree inserts a word (w) in the Binary search tree. The method Create-
    BinSrchTree creates a binary search tree by repeated calls to InsertionBinSrchTree to insert elements
    of text. The method LinesWordInBinSrchTree traverses the Binary search tree inorder and displays the
    words with the lines in which each appears.
    >>>>>>>>>>>>>>>>>>>>>>
    //InsertionBinTree is of type BinSearchTreeWordNode
    BinSrchTreeWordNode InsertionBinSrchTree(String w, int line,                                             BinSrchTreeWordNode bst)
    //First a check must be made to make sure that we are not trying to //insert a word into an empty tree. If tree is empty we just create a //new node.
         If (bst == NULL)
                   System.out.println(“Tree was empty”)
         For (int rows =0; rows <= 6; rows++)
                   For (int cols = 0; cols <= 4; cols++)
                        Textcont[i][j] = w

    What is the purpose of this thread? You are yet to ask a question... Such a waste of time...
    For future reference use CODE TAGS when posting code in a thread.
    But again have a think about how to convey a question to others instead of blabbering on about nothing.
    i think it does not get any harder than this.What is so difficult to understand. Google an implementation of a binary tree using a single array. Then you can integrate this into the required 2-dimension array for your linked list implemented as an array in your 2-d array.
    Mel

  • Java question help (applying binary search)

    please show me how do i apply a binary search inside this program where i can use the binary serach to search for the book author or book title
    // objectSort.java
    // demonstrates sorting objects (uses bubble sort)
    // to run this program: C>java libmainsys
    class libary
    private String booktitle;
    private String bookauthor;
    private String publisher;
    private int yearpublished;
    private int edition;
    private int nofcop;
    public libary(String title, String author, String pub, int yrpub, int edt, int nfcp)
    {                // constructor
    booktitle = title;
    bookauthor = author;
    publisher = pub;
    yearpublished = yrpub;
    edition = edt;
    nofcop = nfcp;
    public void displaylibary()
    System.out.print(" Book Title: " + booktitle);
    System.out.print(", Book Author: " + bookauthor);
    System.out.print(", Book Publisher: " + publisher);
    System.out.print(", Year Published: " + yearpublished);
    System.out.print(", Edition: " + edition);
    System.out.println(",No Of Copies : " + nofcop);
    public String getLast() // get title
    { return booktitle; }
    } // end class libary
    class ArrayInOb
    private libary[] nfcp; // ref to array ypub
    private int nElems; // number of data items
    public ArrayInOb(int max) // constructor
    nfcp = new libary[max]; // create the array
    nElems = 0; // no items yet
    // put libary into array
    public void insert(String title, String author, String pub, int yrpub, int edt, int nofcop)
    nfcp[nElems] = new libary(title, author, pub, yrpub, edt, nofcop);
    nElems++; // increment size
    public void display() // displays array contents
    for(int j=0; j<nElems; j++) // for each element,
    nfcp[j].displaylibary(); // display it
    System.out.println("");
    public void bubbleSort()
    int i, j;
    libary temp;
    for (i = nElems-1; i >= 0; i--)
    for (j = 1; j <= i; j++)
    if (nfcp[j-1].getLast().compareTo(nfcp[j].getLast())>0)
    temp = nfcp[j-1];
    nfcp[j-1] = nfcp[j];
    nfcp[j] = temp;
    } // end class ArrayInOb
    class libmainsys
    public static void main(String[] args)
    int maxSize = 1000; // array size
    ArrayInOb arr; // reference to array
    arr = new ArrayInOb(maxSize); // create the array
    arr.insert("Java_how__to_program", "Patty_John", "Deitel", 2001, 1, 430);
    arr.insert("System_Design", "Dexter_Smith", "Thomson", 2002, 3, 450);
    arr.insert("Program_Design", "Lorraine_Paul", "About", 1996, 2, 196);
    arr.insert("Computer_Architecture", "Paul_Andrew","Dzone", 2006, 5, 199);
    arr.insert("Visual_Basic_How_To_ Program", "Tom_Jones", "Jeffereson_publication", 2007, 4, 207);
    arr.insert("Information_ Management", "William_Peter", "Mcgraw_Hill", 1995, 3, 204);
    arr.insert("Sofware_ Application", "Henry_Sam", "Pearson", 2001, 6, 278);
    arr.insert("English", "Samantha_Julia", "James_Hill", 2005, 1, 200);
    arr.insert("Web_Publishing", "Audrey_Cynthia", "Surg", 2004, 3, 201);
    arr.insert("Human_Computer_Interaction", "Tony_Edward", "Telde", 2003, 3, 199);
    System.out.println("Before sorting:");
    arr.display(); // display items
    arr.bubbleSort(); // insertion-sort them
    System.out.println("After sorting:");
    arr.display(); // display them again
    } // end main()
    } // end class libmainsys

    I see you haven't worked out bubbleSort either. Since binary search only works on sorted arrays, I suggest you start there. Do you have the algorithms somewhere?
    If you really need to be able to search using either author or title, I suggest you create 2 Comparators that compare using the desired property. Comparator is just an interface that defines methods to compare 2 objects. You have to write your own implementation of it to compare library objects. You'll always have to sort and search using the same Comparator.

  • Binary search in java

    Hi,
    I keep getting a java.lang.ClassCastException with these two classes when I try to perform a binary search. Any tips?
    Phonebook class:
    =============
    import java.util.*;
    public class Phonebook
    private static long comparisons = 0;
    private static long exchanges = 0;
         public static void main (String[] args)
         // Create an array of Phonebook records
         PhoneRecord[] records = new PhoneRecord[10];
         records[0] = new PhoneRecord("Smith","Bob", 1234367);
         records[1] = new PhoneRecord("Jones","Will", 1234548);
         records[2] = new PhoneRecord("Johnson","Frank", 1234569);
         records[3] = new PhoneRecord("Mc John","Pete", 1234560);
         records[4] = new PhoneRecord("OBrien","Frank", 1234571);
         records[5] = new PhoneRecord("OConnor","Joe", 1234572);
         records[6] = new PhoneRecord("Bloggs","Ricky", 1233570);
         records[7] = new PhoneRecord("empty","empty", 8888888);
         records[8] = new PhoneRecord("empty","empty", 9999999);
         records[9] = new PhoneRecord("Van Vliet","Margreet", 1244570);
         // call menu
         Menu(records);
         } // end main
    //================================================
    // menu
    //================================================
    static void Menu(PhoneRecord[] records)
         int option;
         // menu options
         System.out.println("===========Menu==============================");
         System.out.println("=============================================");
         System.out.println(" ");
         System.out.println("1. Find record (Advanced Search) ");
         System.out.println("2. Quick Search ");
         System.out.println("3. Add a record ");
         System.out.println("4. Show database ");
         System.out.println("5. Sort database ");
         System.out.println("6. Exit     ");
         System.out.println(" ");
         System.out.println("=============================================");
         System.out.println("=============================================");
         System.out.println(" ");
         System.out.println("Choose a number ");
         option = Console.readInt();
         // every menu option has its own method
         if (option == 1)
              FindRecord(records);
         if (option == 2)
              QuickSearch(records);
         else if (option == 3)
              AddRecord(records);
         else if (option == 4)
              ShowDatabase(records);
         else if (option == 5)
              quickSort(records, 0, 9);
              ShowDatabase(records);
         // if 6 then terminate the program
         else
                   System.out.println("Goodbye!");
    } // end of menu
    //=================================================
    // menu option 1: Find a record - using linear search
    //=================================================
    static void FindRecord(PhoneRecord[] records)
    int option;
    do
    // the user can search based on first name or last name
    System.out.println("Do you want to search for:");
    System.out.println("1. First Name");
    System.out.println("2. Last Name");
    System.out.println("3. End search");
    option = Console.readInt();
         // option 1 is search based on first name
         if (option == 1)
              System.out.println("Enter First Name");
              String first = Console.readString();
              int notthere = -1;
              for (int i=0; i < 10; i++)
                   if (first.equals(records.first_Name))
                        System.out.println("----------------------------------");
                        System.out.println(records[i].last_Name + ", " + records[i].first_Name);
                        System.out.println(records[i].phonenumber);
                        System.out.println("----------------------------------\n\n");
                   // if a record is found, the variable notthere will be > -1
                   notthere = i;
              } // end search array
                   // if notthere is -1, then there is no record available
                   if (notthere < 0)
                   System.out.println("------------------------------");
                   System.out.println("No record available");
                   System.out.println("------------------------------\n\n");
         } // end option 1 First Name
         // option 2 allows the user to search based on last name
         else if (option == 2)
              System.out.println("Enter Last Name");
              String last = Console.readString();
              int notthere = -1;
              for (int i=0; i < 10; i++)
                   if (last.equals(records[i].last_Name))
                        System.out.println("----------------------------------");
                        System.out.println(records[i].last_Name + ", " + records[i].first_Name);
                        System.out.println(records[i].phonenumber);
                        System.out.println("----------------------------------\n\n");
                   notthere = i;
                   // if notthere is -1 then there is no record available
                   // if notthere is > -1 then there is a record available
                   } // end search array
                   if (notthere < 0)
                   System.out.println("------------------------------");
                   System.out.println("No record available");
                   System.out.println("------------------------------\n\n");
         } // end option 2 Last Name
         else
              // if the user types in a wrong number, he or she returns to the menu
              Menu(records);
    while (option != 3);
    } // end FindRecord
    //=================================================
    // menu option 2: Quick Search - using binary search
    //=================================================
    static void QuickSearch(PhoneRecord[] records)
         // Sort array - Using Quicksort
         quickSort(records, 0, 9);
         // allow user to enter the last name
         System.out.println("Enter Last Name");
         String last = Console.readString();
         // use binary search to find the target
         int index = binarySearch(records, last);
         // -1 means that there are no records
         if (index == -1)
         System.out.println("------------------------------");
         System.out.println("No record available");
         System.out.println("------------------------------\n\n");
         // print out the record
         System.out.println("----------------------------------");
         System.out.println(records[index].last_Name + ", " + records[index].first_Name);
         System.out.println(records[index].phonenumber);
         System.out.println("----------------------------------\n\n");
         // return to menu
         Menu(records);
    } // end QuickSearch
    public static int binarySearch( Comparable [ ] a, Comparable x )
    int low = 0;
    int high = 9;
    int mid;
    while( low <= high )
    mid = ( low + high ) / 2;
    if( a[ mid ].compareTo( x ) < 0 )
    low = mid + 1;
    else if( a[ mid ].compareTo( x ) > 0 )
    high = mid - 1;
    else
    return mid;
    return -1; // not found
    //=================================================
    // menu option 3: Add a record
    //=================================================
    static void AddRecord(PhoneRecord[] records)
    int option;
    int index = 0;
    // enter details
    do
         // to say that the array is not full yet, I use the variable filled
         int filled = 0;
    System.out.println("Enter the First Name");
    String frst = Console.readString();
    System.out.println("Enter the Last Name");
    String lst = Console.readString();
    System.out.println("Enter the phone number");
    int phn = Console.readInt();
    // search the array for the empty slot
         for (int i=0; i < 10; i++)
              if (records[i].first_Name.equals("empty") && filled == 0)
              records[i].first_Name = frst;
              records[i].last_Name = lst;
              records[i].phonenumber = phn;
              filled = 1;
         // Sort array - Using Quicksort
         quickSort(records, 0, 9);
         // Print out sorted values
         for(int i = 0; i < records.length; i++)
              System.out.println("----------------------------------");
              System.out.println(records[i].last_Name + ", " + records[i].first_Name);
              System.out.println(records[i].phonenumber);
              System.out.println("----------------------------------\n\n");
         System.out.println("Do you want to add more records?");
         System.out.println("1. Yes");
         System.out.println("2. No");
         option = Console.readInt();
         if (option == 2)
              Menu(records);
         // sets the database to full
         int empty = 0;
         for (int i=0; i < 10; i++)
              // empty = 1 means that there is an empty slot
              if (records[i].first_Name.equals("empty"))
                   empty = 1;
         // if the system didn't find an empty slot, the database must be full
         if (empty == 0)
         System.out.println("Database is full");
         option = 2;
         Menu(records);
    while (option != 2);
    } // end AddRecord
    //=================================================
    // menu option 4: Show database
    //=================================================
    static void ShowDatabase(PhoneRecord[] records)
              // shows the entire database
              for (int i=0; i < 10; i++)
                        System.out.println("----------------------------------");
                        System.out.println(records[i].last_Name + ", " + records[i].first_Name);
                        System.out.println(records[i].phonenumber);
                        System.out.println("----------------------------------");
         Menu(records);
    //===============================================
    // Sort array
    //=============================================
    public static void quickSort (Comparable[] a, int left, int right)
         // Sort a[left?right] into ascending order.
         if (left < right) {
         int p = partition(a, left, right);
         quickSort(a, left, p-1);
         quickSort(a, p+1, right);
    static int partition (Comparable[] a, int left, int right)
         // Partition a[left?right] such that
         // a[left?p-1] are all less than or equal to a[p], and
         // a[p+1?right] are all greater than or equal to a[p].
         // Return p.
         Comparable pivot = a[left];
         int p = left;
         for (int r = left+1; r <= right; r++) {
         int comp = a[r].compareTo(pivot);
         if (comp < 0) {
         a[p] = a[r]; a[r] = a[p+1];
    a[p+1] = pivot; p++;          }
         return p;
    } // end class PhoneBook
    PhoneRecord class:
    ================
    public class PhoneRecord implements Comparable
    public int phonenumber;
    public String last_Name;
    public String first_Name;
    public PhoneRecord(String last_Name, String first_Name, int phonenumber)
    this.last_Name = last_Name;
    this.phonenumber = phonenumber;
    this.first_Name = first_Name;
    /* Overload compareTo method */
    public int compareTo(Object obj)
    PhoneRecord tmp = (PhoneRecord)obj;
    // sorting based on last name
    String string1 = this.last_Name;
    String string2 = tmp.last_Name;
    int result = string1.compareTo(string2);
    if(result < 0)
    /* instance lt received */
    return -1;
    else if(result > 0)
    /* instance gt received */
    return 1;
    /* instance == received */
    return 0;

    JosAH wrote:
    prometheuzz wrote:
    bats wrote:
    Hi,
    I keep getting a java.lang.ClassCastException with these two classes when I try to perform a binary search. Any tips?
    ...Looking at your binary search method:
    public static int binarySearch( Comparable [ ] a, Comparable x)I see it expects to be fed Comparable objects. So, whatever you're feeding it, it's not a Comparable (ie: it doesn't implement Comparable), hence the CCE.It's even worse: if an A is a B it doesn't make an A[] a B[].
    kind regards,
    JosMy post didn't make much sense: if there were no Comparables provided as an argument, it would have thrown a compile time error. The problem lies in the compareTo(...) method.

  • Dynamic java applet for binary search tree

    dynamic java applet for deleting an element of a tree at any specified locationin the tree.

    sorry, having thought a bit more about it let me try to be more correct and concrete. say i have feature a at arbitrary chromosome position 7 and features b at positions 1, 2, 3, 5, 6, 9, 10. right now i have to get the closest distance (Math.abs(7-6)) by doing brute force comparison of all values (Math.abs(7-1), Math.abs(7-2), so on). what i want to do is set up a binary tree thus (please forgive poor ASCII):
    5
    2 9
    1 3 6 10
    and get back the keys that the tree tried (since i know that 7 is not in the tree and a traditional binary search e.g. TreeMap.get(new Integer(7)) will return a null). i should get back 5, 9, 6, in an array/ArrayList and be able to find the closest feature b in three comparisons rather than 7. that doesn't seem like much but when you have a million b features the difference between 1000000 comparisons and log2(1000000) is pretty appreciable. so i am wondering if there is an extant class that will give me back the trace of attempted keys through a binary tree as described or, if not, if this would be horribly difficult to implement as an extension of TreeMap.

  • Linear and Binary Searching of Parallel Arrays

    I'm an AP student who used the "Fundamentals of Java" by Lambert/Osborne 3rd Edition. This text book has code that doesn't match anything else I've found in other how-to's, guides, or teach yourself books. Not even online can I find code that matches up with the format used in this book!
    I've got an assignment that wants me to read in a 4 digit account number of N number of customers, places them in two parallel arrays. Data found in two separate txt files. Create a prompt that ask's for customer's account number then displays account balance. Same program for both linear and binary search methods (2 programs).
    I know the search method and how to read the files with a scanner. It is the body of the program that is stumping me. How to call and search the arrays themselves. Any help would be great.

    First of all, you have posted this question in the wrong place. Please post these kinds of general questions in the New to Java forum.
    Second, if you're in an AP class, don't you have a teacher you can ask?
    But anyway, here's the idea
    For a linear search, you go thru the array element by element, and on each element you call equals(x) to see if that element is equal to what you're searching for (note that primitives use == rather than equals)
    For binary search, note first of all that your data MUST BE COMPARABLE (primative or implement the comparable interface) and MUST BE SORTED.
    Then what you can do if go to the middle of the list, and if what you are searching for is less than that element, go to the middle of the first half of the list (if it's greater, go the the middle of the upper half of the list) and keep breaking the list in half until you've found the element or you know its not there.

Maybe you are looking for

  • E65 and BH-214

    I should like know the compatibility between my phone E65 and blue tooth BH-214, tks 

  • Streaming hardware from scratch

    21 years of video production experience. 18 months of operating Windows Media Encoder in conjunction with live, streaming webcasts. I am in initial phase of determining the feasibility of operating my own live, streaming webcast company. In particula

  • Can Not Print any PDF Docs

    I can't print any PDF Documents any more. I checked and have the current version. I have tried to print on two different printers and it still doesn't work. I can print using other programs like MS Word and Excel. Do I need to reinstall?

  • Installing Windows 7 thru Parallels

    I installed Parallels, am am starting to install Window 7 (Professional). Do I use the 32 bit or 64 bit disc?

  • Disp+w/p not running

    Hi, when i start the MMC disp+w/p is showing stopped.plz solve my problem. plz urgent vinnu.