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.

Similar Messages

  • JAVA QUESTIONS HELP!!!!!

    Hi there im a student and have an exam on java coming up next week, i have a few past paper questions that im stuck with if anyone can help that would be great.....
    1.) Java implements generic types by erasure: what does this mean?
    A. The compiler removes references to parameter types and inserts casts wherever return types refer to parameter types.
    B. The programmer must comment out references to parameter types before code is compiled.
    C. The compiler removes any casts that may be type-unsafe. &#1048576;
    D. The compiler removes any references to parameter types and inserts references to the closest super class that will make expressions type-safe.
    E. Any type-unsafe casts to parameter types will be ignored by the interpreter at run-time.
    2.) In Remote method Invocation, what is meant by �marshalling�?
    A. Marshalling is the process of synchronizing all parameters to the method being invoked, in order to
    prevent data corruption arising from the concurrent method call. &#1048576;
    B. Marshalling is the process of sending a copy of the remote object to the client JVM in order to
    invoke its method locally. &#1048576;
    C. Marshalling is the process of sending the state of the client JVM on a byte stream to the remote
    object in order that the JVM can be started as a separate thread on the remote host. &#1048576;
    D. Marshalling is the process of suspending the current thread in the client JVM until a result is obtained
    from the remote method invocation. &#1048576;
    E. Marshalling is the process of sending the state of all parameter instances on a byte stream to the remote object.
    3.)What is the immediate superclass of javax.swing.JFrame?
    A. java.lang.Object &#1048576;
    B. javax.swing.Window &#1048576;
    C. javax.swing.JComponent &#1048576;
    D. java.AWT.Window &#1048576;
    E. java.AWT.Frame
    4.) What is the immediate superclass of javax.swing.JComponent?
    A. java.lang.Object &#1048576;
    B. java.AWT.Component &#1048576;
    C. java.AWT.Container &#1048576;
    D. java.AWT.Window &#1048576;
    E. javax.swing.Object
    5.) Which of the following statements about the java.AWT and javax.swing packages is true?
    A. All components in both packages are thread-safe&#1048576;
    B. Most components in both packages are thread-safe&#1048576;
    C. Most components in java.AWT are thread-safe, but most in javax.swing are not&#1048576;
    D. Most components in javax.swing are thread-safe, but most in java.AWT are not&#1048576;
    E. No components in either package are thread-safe&#1048576;
    6.) Which of the following best describes how AWT events are handled in Java?
    A. There is a special thread that handles all AWT events. &#1048576;
    B. Each AWT event causes a new thread to be created to handle that event. &#1048576;
    C. All AWT events are handled in the main thread. &#1048576;
    D. The programmer must explicitly create one thread to handle all AWT events. &#1048576;
    E. For each AWT event, the programmer must explicitly create a thread to handle that event. &#1048576;
    7.) Which of the following best describes how component-generated events can be handled in Java?
    A. All component-generated events are handled automatically by the Java interpreter. &#1048576;
    B. The programmer creates instances of appropriate listener classes, and registers these instances with
    the component; when the component generates an event, the relevant methods of all registered
    listeners are executed. &#1048576;
    C. The programmer creates instances of appropriate listener classes, and registers these instances with
    the component; when the component generates an event, one of the registered listeners is chosen by
    the interpreter and the relevant method of that instance is executed. &#1048576;
    D. The programmer must declare a subclass of the component and add one method for each type of
    event the component can generate; when the component generates an event, the appropriate method
    is executed. &#1048576;
    E. Each component class has event-handling methods; the programmer declares a subclass of the
    component and overrides those methods; when the component generates an event, the overridden
    method is executed. &#1048576;
    Any help would b great thanks guys. Andy

    1.) Java implements generic types by erasure: what
    does this mean?
    A. The compiler removes references to parameter types
    and inserts casts wherever return types refer to
    parameter types.
    B. The programmer must comment out references to
    parameter types before code is compiled.
    C. The compiler removes any casts that may be
    type-unsafe. &#1048576;
    D. The compiler removes any references to parameter
    types and inserts references to the closest super
    class that will make expressions type-safe.
    E. Any type-unsafe casts to parameter types will be
    ignored by the interpreter at run-time.None of the above (assuming this is not a Google translation of some non-English text).
    2.) In Remote method Invocation, what is meant by
    �marshalling�?
    A. Marshalling is the process of synchronizing all
    parameters to the method being invoked, in order to
    prevent data corruption arising from the concurrent
    method call. &#1048576;
    B. Marshalling is the process of sending a copy of
    the remote object to the client JVM in order to
    invoke its method locally. &#1048576;
    C. Marshalling is the process of sending the state of
    the client JVM on a byte stream to the remote
    object in order that the JVM can be started as a
    separate thread on the remote host. &#1048576;
    D. Marshalling is the process of suspending the
    current thread in the client JVM until a result is
    obtained
    from the remote method invocation. &#1048576;
    E. Marshalling is the process of sending the state of
    all parameter instances on a byte stream to the
    remote object.None of the above. Although there is one answer that at least describes how Marshalling is used.
    3.)What is the immediate superclass of
    javax.swing.JFrame?
    A. java.lang.Object &#1048576;
    B. javax.swing.Window &#1048576;
    C. javax.swing.JComponent &#1048576;
    D. java.AWT.Window &#1048576;
    E. java.AWT.FrameAt least this one does have the correct answer. It's in the API docs, so I guess it'd be hard to be wrong.
    4.) What is the immediate superclass ofDitto.
    5.) Which of the following statements about the
    java.AWT and javax.swing packages is true?
    A. All components in both packages are
    thread-safe&#1048576;
    B. Most components in both packages are
    thread-safe&#1048576;
    C. Most components in java.AWT are thread-safe, but
    most in javax.swing are not&#1048576;
    D. Most components in javax.swing are thread-safe,
    but most in java.AWT are not&#1048576;
    E. No components in either package are
    thread-safe&#1048576;Again, none of the above.
    6.) Which of the following best describes how AWT
    events are handled in Java?
    A. There is a special thread that handles all AWT
    events. &#1048576;
    B. Each AWT event causes a new thread to be created
    to handle that event. &#1048576;
    C. All AWT events are handled in the main thread.
    &#1048576;
    D. The programmer must explicitly create one thread
    to handle all AWT events. &#1048576;
    E. For each AWT event, the programmer must explicitly
    create a thread to handle that event. &#1048576;One answer is almost, sort of, correct. Wow.
    I can understand why you're having problems answering these questiosn. Well, there's no excuse for the questions that come out fo the Javadocs, but for the others ... it explains a lot about the quality of recent graduates.

  • Stupid Java Question (Help Needed!!!)

    I have a piece of Java Code that dynamically builds a SQL statement (including VARCHAR2 columns). Oracle gives an error if my string has a single quote in it. I need to replace each single quote with two single quotes in Java, i.e. I need a Java equivalent of PL/SQL REPLACE function.
    Java str.replace only replaces an individual character (see below).
    String l_str = "O'Hara";
    String l_str2 = l_str.replace('\'', '\'');
    I need to replace "O'Hara" with "O''Hara". Any help is appreciated

    Please don't post same question on both forums.
    Please find the answer at:
    Re: ORA-09004

  • Simple java question, help please

    please help
    -i am just starting out in java and im havin an early problem. Im trying to run a small java script from a commant prompt but im getting the following error after i enter this command at my prompt
    c:\javatest>javac HelloARP.java
    javac is not as an internal or external command, operable program or batch file.
    when i enter
    c:\java -version
    i get the following message: registry key software\javasoft\java runtime enviornment\current version has value of 1.1 but 1.4 is requiured
    error: could not find java.dll
    error: could not find java 2 runtime enviornment
    -im sure this is a simple error on my part. all im trying to do is run my first lil program that i saved in notepad, its only 5 lines long. here is the lil test program im trying to execute
    class HelloARP {
    public static void main (String[] arguments) {
    System.out.println("What's good ARP?");
    - all responses and help are welcomed. Thank you ahead of time for anyone that can help me get started.

    Hi
    First of all uninstall your current JDK installation, if you can get to the registry delete the registry entries for the old version of java which was there on your machine.
    Now do a fresh install of your j2sdk1.4.1, make sure that you will install the JRE with the J2SDK1.4.1.
    Once you are done, set your classpath in autoexec.bat if you are using Windows 95/98
    or set your environment variables if you are using Win NT/2000/XP.
    If using solaris or other unix flavors see the included installation instructions provided.
    Let me if you face the same problem.
    Thanks
    Swaraj

  • Question about binary search tree

    i was asked to do a programe that generating 1000 random integer numbers between 1 - 50, storing each unique number and it's corresponding occurrence into a binary search tree and output them in asending order. Therefore, before, adding the new number into the tree, i have to compare it with others that have been stored in the tree. and i did it in the following code segment.
    public void compare(int number)
       NumberObject newNumObj = new NumberObject(number);
       boolean b = true;
       if(isEmpty())
        root = new BinarySearchTreeNode(newNumObj, null, null); //assuming BSTNode class in somewhere else
       else
        b = find(root, newNumObj);
        if(b == false)
         add(newNumObj);
    private boolean find(BinarySearchTreeNode node, NumberObject newNumObj)
        int relation = ((Comparable)newNumObj).compareTo(node.getObject());
        //******************** QUESTION IS HERE ******************
        if(relation == 0) 
         (node.getObject()).setCount(); //increase that number object's account
          newNumObj = null;  //recycle newNumObj if it's the same as one stored in the tree
          return true;
       //****************** ENDS QUESTION ********************************
        else if(relation > 0)
          find(node.right, newNumObj);
        else if(relation < 0)
          find(node.left, newNumObj);
       return false;
    my question is can i say the new number is the same as the one that already stored in the tree according to the above code? i am not sure cauz there are two attributes: the number and it's frequency stored in one numberObject. and the compareTo method just dealing with the numbers, but nothing particular associated with it's account. so, could anyone help me work out this puzzle? help would be greatly appreciated!

    Not sure whether this is what you want.. But may be it will help....
    import java.util.*; 
    public class Rand{
         public static void main(String arg[]){
              new Rand();      
         Rand(){
              Random random=new Random();
              int ranNo;
              TreeMap map=new TreeMap();
              Integer in;
              for(int i=0;i<1000;i++){
                   ranNo= random.nextInt() ;      
                   ranNo=Math.abs(ranNo);
                   ranNo%=50;
                   in=new Integer(ranNo);
                   if(!(map.containsKey(in)))
                        map.put(in,i+""); 
              Iterator iter=map.keySet().iterator();
              Integer key;
              while(iter.hasNext()){
                   System.out.print( (key=(Integer)iter.next()) + "  ");
                   System.out.println(map.get(key).toString());
    }appu

  • Creating A Binary search algorithm !!!! URGENT HELP

    hi ..
    i;m currently tryin to create a binary search algorithm ..
    the user should be able to input the size of the array
    and also the key that he would like to find.
    it also has to have to ability to measure the run time of the algorithm.. it how long it too the algorithm to search through the array and find they key..
    i have created 3 classes
    the first class is the binary search class
    which is the mathamatical side of things
    the second class is the Array
    this creates an array selection a random first number
    and then incrementing from there, so that its a sorted array
    the third class is the binary search class
    which is my main class.
    this class should take the users input
    and pass it to the array
    and the binary seach accordingly
    it should also measure the running time, from when it passes the array
    to the binary search class
    i am having a really hard time creating this last class.
    i have created the other 2 successfully
    the codes for the binary search class is as follows
    public class BinarySearch
         static int binSearch(int[] array, int val)
             // setting the start and the end of the array
              int low = 0, high = array.length;
              //While loop
              while(low <= high) {
              // How to find the mid point      
                  int mid = (low + high)/2;
                   // if the mid point is the value return the value
                  if(array[mid] == val) {
                        return mid;
                   // if the value is smaller than the mid point
                   // go search the left half
                   } else if(array[mid] > val) {
                        high = mid - 1;
                   //if the value is greater then the mid point
                   // go search the right half
                   } else if(array[mid] < val) {
                        low = mid + 1;
              // if value is not found return nothing
              return -1;
    }and the code for the Array class is as follows
    import java.util.Random;
    public class RandomSortedArray
        public int[] createArray(int length)
            // construct array of given length
            int[] ary = new int[length];
            // create random number generator
            Random r = new Random();
            // current element of the array; used in the loop below.  Starts at
            // -1 so that the first element of the array CAN be a 0
            int val = -1;
           for( int i = 0; i < length; i++)
                val += 1 + r.nextInt(10);
                ary[i] = val;
            return ary;
    }can some pne please help me create my binarysearchTest class.
    as i mentioned before
    it has to take the users input for the array size
    and the users input for the value that they want to find
    also needs to measure the running time
    thanks for all ur help in advance

    import java.util.*;
    public class AlgorithmTest
         public static void main(String args[])
             long StartTime, EndTime, ElapsedTime;
             System.out.println ("Testing algorithm");
             // Save the time before the algorithm run
             StartTime = System.nanoTime();
             // Run the algorithm
             SelectionSortTest1();
             // Save the time after the run
             EndTime = System.nanoTime();
             // Calculate the difference
             ElapsedTime = EndTime- StartTime;
             // Print it out
             System.out.println("The algorithm took " + ElapsedTime + "nanoseconds to run.");
        }this is the code i managed to work up for measuring the time..
    how would i include it into the main BinarysearchTest Class

  • 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

  • Binary Search Help

    Below is the coding for the binary search:
    public class Binary_Search_
    public int binarySearch(int arr[],int key)
    int low=0;
    int high=arr.length-1;
    while(low<=high)
    int middle=(low+high)/2;
    if(key==arr[middle])
    return middle;
    else
    if(key<arr[middle]) high=middle-1;
    else low=middle+1;
    return -1;//not found
    The only thing is that for the binary search the array must be sorted so what could I add to the start of the coding to quickly sort the array.
    You must think this is a simple question but im new to java!

    Another thing..
    Try rethinking your algorithm through.
    int middle=(low+high)/2will not always hit the center/middle/sweet spot (or what you would call it) of your array.
    If low was 2 and high was 5, your middle would be 3 (yes, 3), and if you are unlucky to have an array like this
    1, 2, 3, 5, 7, 11, 13, 17, 19your code would return -1 if you were searching for 5.
    And that's just one of a jillion possibilities.

  • [Help] Binary Search

    I want to do a binary search on a sorted array list.
    My question is,
    In the java.util package, there is a pre-written methods, Arrays.binarySearch() which I can use it to do the searching straight forward. What I concern here, if I write the binary search algorithm myself, will it be fastest?
    Let's assume, there are only integers in the array, and the binary search algorithm that I am going to write in traditional way that widely used today.

    Whenever there is a method available in the API we need not write the method once again. All the way whatever we write may contain some pit-falls and it may fail some where at the same it won't be that much efficient also.

  • Binary search tree help...

    Ok, maybe someone can help me with this one. Here's the code that I'm having trouble with:
      public Object findValue(Comparable aKey)
        Node result = (Node) findByKey(aKey);
        if(result != null && result.getNodeKey() == aKey)
          return result.getNodeData();
        else
          return null;
      }The problem is in the condition for the if statement, particularly, "result.getNodeKey() == aKey". I've checked both values for result.getNodeKey() and aKey, and they are both the same, but the program gives ma a false result, which sends it straight to the "return null;" statement. Any thoughts as to why it might do this?

    I just found another trouble spot. Here's the code this time:
      public boolean delete(Comparable aKey)
        Node result = (Node) findByKey(aKey);
        if(result != null && result.getNodeKey().equals(aKey))
          Node currentNode = rootNode;
          Node parentNode = null;
          boolean found = false;
          while(!found && currentNode != null)
            if(aKey.compareTo(currentNode.getNodeKey()) < 0)
              parentNode = currentNode;
              currentNode = (Node)currentNode.getLeftChild();
            else
              if(aKey.compareTo(currentNode.getNodeKey()) > 0)
                parentNode = currentNode;
                currentNode = (Node) currentNode.getRightChild();
              else
                found = true;
          if (parentNode == null)
            //here's where I need assistance
            return true;
          else
            parentNode.setLeftChild((Node) currentNode.getLeftChild());
            Node holderNode = (Node) currentNode.getLeftChild();
            holderNode.setRightChild((Node) currentNode.getRightChild());
            return true;
        else
          return false;
      }I'm trying to delete from the binary search tree, and I'm not sure how to adjust for deleting the top of the tree (rootNode, in this case) before the rest of the tree is gone. Any ideas?

  • 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.

  • Basic binary search tree question

    Hi,
    I was just wondering, if there's a binary search tree that holds objects can the binary search tree be based on any of the attributes in those objects.
    So for example say we have a Person object and it has the attributes name, age, and height. Can we make a binary search tree based on the age or a search tree based on just the height.
    And lastly how would that be done in the comparable method.
    Thanks.

    Of course it depends on what (and whether) the Person class implements for Comparable. If you want to base the tree on the default comparison (i.e., the one that compareTo does) then you don't need a separate Comparator.
    When you write your binary tree implementation, it's wise to make it smart enough to either take a Comparator, or to use the default comparison (if the objects being tracked implement Comparable).
    Note that Comparators and Comparable have nothing to do with trees per se. It's not like a tree necessarily needs one or the other. It's simply very smart to use the existing Java framework to determine an order among objects.

  • Binary Search Tree Question - Duplicate Entries

    I am doing a project for school where I have to parse a web page into a binary search tree. The problem I'm encountering is that the tree is not supposed to have duplicate entries. Instead, each node has a count variable which is supposed to be incremented if a duplicate node attempts to be inserted. I have everything else working but I can't seem to get the count to increment.
    Here is the insert method in my BinarySearchTree class:
        public void insert( String s )
            BTNode newNode = new BTNode();
            newNode.sData = s;
            newNode.count = 1;
            if( root == null )
                root = newNode;
            else
                BTNode current = root;
                BTNode parent;
                while( true )
                    parent = current;
                    if( s.compareTo( current.sData ) < 0 )
                        current = current.leftChild;
                        if( current == null )
                            parent.leftChild = newNode;
                            return;
                    else if( s.compareTo( current.sData ) >= 0 )
                        current = current.rightChild;
                        if( current == null )
                            parent.rightChild = newNode;
                            return;
        }Thanks for the help!

    runningfish007 wrote:
    I am doing a project for school where I have to parse a web page into a binary search tree. The problem I'm encountering is that the tree is not supposed to have duplicate entries. Instead, each node has a count variable which is supposed to be incremented if a duplicate node attempts to be inserted. There are two ways I can think to do this simply. Presumably you have a search method that returns a BTNode for a given String? You could use that to find out if the tree already contains that String. If so, you have that Node, so you can just increment it's counter. If not, then go through and insert it normally, knowing that you won't encounter a duplicate.
    The second is to look at the children for each node as you come to it. If either matches the given string, then you've found a duplicate. Otherwise, either insert the new element there (if that's the location it belongs), or continue down the tree.
    Either way, I'd rewrite this as a recursive method. It's much simpler. What you do is check if the new element should be a child of the current node. If so, attach it and return. Otherwise, call the method on the correct child node. No looping necessary.

  • Binary search question with objects

    Hi
    I have a class called MyClass which is as below
    public class MyClass
    String from;
    String to;
    double d;
    // with getter and setter method
    }I create a ArrayList of MyClass,
    List<MyClass> list = new ArrayList();
    list.add(myClass);
    //add about 8000 myClass object from database; I want to do a search for object from, to;
    I have been doing
    for(MyClass myClass:list)
    if(myClass.equals(from) && myClass.equals(to))
    return myClass;
    }Rather i would like to do a randomSearch, how can i do it,
    will it be faster, then going through all the list
    Any ideas

    Binary search requires that your list is sorted, so you'll have to implement Comparable<MyClass>, and use Collections.sort(list) before doing the search.
    I also think that this:
    if(myClass.equals(from) && myClass.equals(to))implies that you aren't using equals() properly. I think it should look more like this:
    if(myClass.getFrom().equals(from) && myClass.getTo().equals(to))Here's a quick and dirty example of implementing Comparable and doing a binary search:
    static class MyClass implements Comparable<MyClass> {
         private String from, to;
         public MyClass(String from, String to) {
              this.from = from;
              this.to = to;
         public String getFrom() { return from; }
         public String getTo() { return to; }
         public int compareTo(MyClass obj) {
              int toComp = to.compareTo(obj.getTo());
              int fromComp = from.compareTo(obj.getFrom());
              return toComp - fromComp;
         public boolean equals(Object obj) {
              if (obj instanceof MyClass == false) {
                   return false;
              return ((MyClass)obj).getFrom().equals(from) && ((MyClass)obj).getTo().equals(to);
         public int hashCode() {
              return from.hashCode() + to.hashCode();
         public String toString() {
              return "from: "+from+", to: "+to;
    public static void main(String[] args) {
         int num = 5;
         List<MyClass> tests = new ArrayList<MyClass>();
         for (int i = 0; i < num; ++i) {
              MyClass test = new MyClass(i+"", (i*2)+"");
              tests.add(test);
         Collections.sort(tests);
         for (MyClass test : tests) {
              System.out.println(test);
         MyClass theTest = new MyClass("4", "8");
         int index = Collections.binarySearch(tests, theTest);
         MyClass result = tests.get(index);
         System.out.println("index: "+index+", result: "+result);
    }Hope that helps.

  • 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.

Maybe you are looking for

  • How merge query results from joined table into one additional column

    <code> Here is example TABLE A: id | value 1 | a 2 | a 3 | b TABLE B id | id_in_table_a | value 1 | 1 | d 2 | 1 | e 3 | 2 | g </code> this select should get all columns from table A where value = 'a' and all values related to this record from B merge

  • Error in VL10D

    Dear guru. I try to create a delivery using VL10D from a return purchase order. I got this error : Incompletion: Vendor: Account Number of Vendor or Creditor (VBPA-LIFNR), error group: 08 Message no. VU014 Do you help me ?

  • Cyrptography question.

    I'm trying to make an encryption program that uses the Rail Fence encryption string. If you don't know what that is please visit http://www.cs.uct.ac.za/courses/Course1/110/Tut8/concepts.htm Anyhow what I'm trying to do is create 2 methods. The first

  • My x6 cant connect to wlan...

    hi. recently i have problem with my wlan connection..before this everything is ok..i have no idea how suddenly it`s occured..firstly i thought maybe my wlan at home is prob so i trying using free wifi at cafe and kfc..but still cant connect..it said

  • ITunes not showing the file wich is playing

    when using the grid albums view whenever i access an album and start playing a track, it doesnt show the little gray arrow next to it and the speaker, so i cant see in the playlist which is the one thats being played if i use coverflow or simple play