Binary search question

Hi,
I want to use binary search in my code, just not sure, how to do it right.
Let's say  I have an IT with columns A B C D.
I want to search this table first based on value in A and later based on B.
How should I sort this table?
>sort IT by A B
>read table with key A = '1' binary search
>read table with key B = 'X' binary search
or
>sort IT by A
>read table with key A = '1' binary search
>sort IT by B
>read table with key A = 'X' binary search
What happens, if I sort this table by A and let the system search based on value in B?
Thank you,
Olian

>
Olian Saludew wrote:
>sort IT by A
>read table with key A = '1' binary search
>sort IT by B
>read table with key B = 'X' binary search
That is the way to go (I corrected the typo).
Binary search is only effective when the table is sorted by the search fields. It only makes sense though if you perform multiple reads after sorting (e.g. inside a loop), since sorting itself costs some processing time.
Thomas

Similar Messages

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

  • 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

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

  • Hash Table/Binary Search Tree question

    I'm creating a hash table that uses a Binary Search Tree in each element to handle collisions. I isolated the problem to where and how it occurs to two lines of code; here is the relevant code(There is a working method "insert(String s)" in the BinarySearchTree class):
    x = new BinarySearchTree[size];
    x[0].insert("pppppp");When I try to insert ANY String into ANY array element of x (not just 0), I get a NullPointerException. Keep in mind that BinarySearchTree works perfectly when it's not an array.
    Message was edited by:
    rpelep

    x = new BinarySearchTree[size];
    x[0].insert("pppppp");You should know that when you allocate an array of objects, each entry is initialized to null.
    Instead, you must do this:
    x = new BinarySearchTree[size];
    for(int i=0; i<size; i++) {
       x[i] = new BinarySearchTree();
    }After that, you can then do
    x[0].insert("pppppp");

  • 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

    I am writing my own implementation of a binary search tree and one of the methods I am having issues with writing is a getRootNode() method.
    I am wondering A if there is any API doc on Binary search trees and B What the method would look like for a getRootNode()
    I wrote the following two methods
    //getEntry
        public E getEntry(E entry)
            return findEntry(getRootNode(), entry);
    //findEntry
       private E findEntry(BinarySearchTreeNode<E> rootNode, E entry)
            E resualt = null;
            if (rootNode == null)
                E rootEntry = rootNode.getElement();
                if (entry.equals(rootEntry))
                    resualt = rootEntry;
                else if(entry.compareTo(rootEntry) < 0)
                    resualt = findEntry(rootNode.getLeft(), entry);
                else
                    resualt = findEntry(rootNode.getRight(), entry);
            return resualt;
    //getRootNode -- this is where I am lost
        private BinarySearchTreeNode<E> getRootNode() {
            // TODO Auto-generated method stub
            return null;
        }Any Ideas?

    user8974754 wrote:
    initialized root
        private BinarySearchTreeNode<E> root;
    That doesn't initialize it. That just declares a member variable named root. To initialize it, you have to do root = something, either on the line where you declare it or elsewhere. Until then, it will have its default value of null.
    >
    So then I am assuming then the code would be
    //Going based on some other code
    private BinarySearchTreeNode<E> getRootNode() {
    if (root != null)
    return root;
    else
    return null;
    That's the same as just return root; If it's not null, you return it, and if it is null, you return null, which is the same as returning root, since, as we just established, root is null.
    Edited by: jverd on Dec 13, 2010 5:02 PM

  • 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 need clarification

    Hi All,
      I am facing a problem here in binary search. I will try to explain the situation with an example.
    Internal table : it_vbap
    Fields :  vbeln   posnr   qty
    Index 1  100      10       5
    index 2  100      10       5
    index 3  100      20       5
    index 4  100      20       5
    index 5  100      30       5
    index 6  100      30      5
    the abap code is this.
    sort it_vbap by vbeln posnr.
    read table it_vbap into ls_vbap with ket
                   vbeln  = ls_vbap-vbeln
                   psonr = ls_vbap-posnr
                   binary search.
    If sy-subrc  = 0.
    write : 'index :' sy-tabix.
    endif.
    My question here is does it always write index 1,3,5 (means in the all the case it should return the first record  ), otherwise it can also return 1, 3, 6.
    Pay attendtion the posnr are the same for every two records.
    The internal table not only contains 6 six records , my question was however not depends on the number of records in the internal table, the binary search will return the first sorted key record in the table or not.
    Please post your views.
    Thanks & regards,
    Vijay

    Hi Vinay,
    It is simple.
    This depends on your select query. 
    CASE 1: If you use select ..into table.....,  then there wil be nothing in your header ls_vbap. Now if you execute READ stmt..you will get nothing.
    CASE 2: If you use Select..... into ls_vbap.....append ls_vbap....clear ls_vbap.....endselect.   In this case also the output of READ will be nothing because you are clearing header.  So while READ stmt you are comparing ls_vbap-vbeln and ls_vbap-posnr , as nothing in it you will get nothing
    CASE 3: If you use case 2 without CLEAR stmt then always you will get the index of the last fetched record...i.e., the last record of the internal table before sorting..
    I think it is helpful for you....if you are not clear just reply me

  • How to use a standard library binary search if I'm not searching for a key?

    Hi all,
    I'm looking for the tidiest way to code something with maximum use of the standard libraries. I have a sorted set of ints that represent quality levels (let's call the set qualSet ). I want to find the maximum quality level (choosing only from those within qualSet ) for a limited budget. I have a method isAffordable(int) that returns boolean. So one way to find the highest affordable quality is to start at the lowest quality level, iterate through qualSet (it is sorted), and wait until the first time that isAffordable returns false. eg.
    int i=-1;
    for (int qual : qualSet) {
         if !(isAffordable(qual))
              return i;
         i++;
    }However isAffordable is a slightly complicated fn, so I'd like to use a binary search to make the process more efficient. I don't want to write the code for a binary search as that is something that should be reused, ideally from the standard libraries. So my question is what's the best way of reusing standard library code in this situation so as to not write my own binary search?
    I have a solution, but I don't find it very elegant. Here are the important classes and objects.
    //simple wrapper for an int representing quality level
    class QualityElement implements Comparable<QualityElement>
    //element to use to search for highest quality
    class HiQualFinderEl extends QualityElement {
         HiQualFinderEl(ComponentList cl) {...}
    //class that contains fair amount of data and isAffordable method
    class ComponentList {
         boolean isAffordable(int qual) {...}
    //sorted set of QualityElements
    TreeSet<QualityElement> qualSet When you create an instance of HiQualFinderEl, you pass it a reference to a ComponentList (because it has the isAffordable() method). The HiQualFinderEl.compareTo() function returns 1 or -1 depending on whether the QualityElement being compared to is affordable or not. This approach means that the binary search returns an appropriate insertion point within the list (it will never act as if it found the key).
    I don't like this because semantically the HiQualFinderEl is not really an element of the list, it's certainly not a QualityElement (but it inherits from it), and it just feels ugly! Any clever suggestions? Btw, I'm new to Java, old to C++.
    If this is unclear pls ask,
    Andy

    Thanks Peter for the reply
    Peter__Lawrey wrote:
    you are not looking for a standard binary searchI'm not using a binary search in the very common I'm searching for a particular key sense, which is the Collections.binarySearch sense. But binary searches are used in other situations as well. In this case I'm finding a local maximum of a function, I could also be solving f(x)=0... is there a nice generic way to handle other uses of binary search that anyone knows of?
    I would just copy the code from Collections.binarySearch and modify itI have this thing about reusing; just can't bring myself to do that :)
    It would be quicker and more efficient than trying to shoe horn a solution which expects a trinary result.Not sure I understand the last bit. Are you referring to my bastardised compareTo method with only two results? If so, I know, it is ugly! I don't see how it could be less efficient though???
    Thanks,
    Andy

  • Read Itab binary search not working.

    Hi,
    I have the following issue:
    From a table, I am picking up 5 fields into an internal table (in the correct sequence):
    A B C D E.
    Now, I am sorting the above internal table as follows:
    sort itab by A B C descnding.
    Now, I am writing the read stmt as follows:
    read table itab into wa_itab with key
                                  A = var1
                                  B = var2
                                  C = car3
                                 Binary Search.
    But, the read fails in most of the cases even though the exact values exist in the itab. It does not fail always, but fails for majority of the cases, though the exact matches are present in the itab.
    If I remove the Binary Search option, it works fine.
    Could you please let me know if I am missing out on anything here?
    Please let me know if any more information is needed.
    Thank You,
    Anjana Banerjee

    Hi anjana,
    please do not ask questions before reading the online help:
    ["The standard table must be sorted in ascending order by the specified search key. "|http://help.sap.com/saphelp_nw73/helpdata/en/fc/eb373d358411d1829f0000e829fbfe/frameset.htm]
    Regards,
    Clemens

  • 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 tree errors

    MORE A CRY FOR HELP THEN A QUESTION-THANKS!
    I'm having some diffucilites debugging errors produced by my binary search tree class. Spent alot of time trying correct them but just doesn't seem to be working for me :|!. I'm working with two main classes BinaryNode and BinarySearchTree.
    class BinaryNode<AnyType> extends BinarySearchTree
        // Constructor
        BinaryNode(AnyType theElement)
            element = theElement;
            left = right = null;
          // Data; accessible by other package routines
        AnyType             element;  // The data in the node
        BinaryNode<AnyType> left;     // Left child
        BinaryNode<AnyType> right;    // Right child
    public class BinarySearchTree<AnyType extends Comparable<? super AnyType>>
          /** The tree root. */
        protected BinaryNode<AnyType> root;
        private int[] unsorted = new int[] {3,6,7,2,1};
         * Construct the tree.
        public BinarySearchTree()
         root = null;
         * Insert into the tree.
         * @param x the item to insert.
         * @throws DuplicateItemException if x is already present.
        public void insert(AnyType x)
            root = insert(x, root);
         * Remove from the tree..
         * @param x the item to remove.
         * @throws ItemNotFoundException if x is not found.
        public void remove(AnyType x)
            root = remove(x, root);
         * Remove minimum item from the tree.
         * @throws ItemNotFoundException if tree is empty.
        public void removeMin()
            root = removeMin(root);
         * Find the smallest item in the tree.
         * @return smallest item or null if empty.
        public BinaryNode<AnyType> findMin()
         //uses a helpler method that iterates over the left hand of the binary tree
            return(findMin(root));
         * Find the largest item in the tree.
         * @return the largest item or null if empty.
        public BinaryNode<AnyType> findMax()
            return (findMax(root));
         * Find an item in the tree.
         * @param x the item to search for.
         * @return the matching item or null if not found.
        public AnyType find(AnyType x)
            return elementAt(find(x,root));
         * Make the tree logically empty.
        public void makeEmpty()
            root = null;
         * Test if the tree is logically empty.
         * @return true if empty, false otherwise.
        public boolean isEmpty()
            return root == null;
         * Internal method to get element field.
         * @param t the node.
         * @return the element field or null if t is null.
        public AnyType elementAt(BinaryNode<AnyType> t)
            return t == null ? null : t.element;
         * Internal method to insert into a subtree.
         * @param x the item to insert.
         * @param t the node that roots the tree.
         * @return the new root.
         * @throws DuplicateItemException if x is already present.
        protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> t)
            if(t == null) {
                t = new BinaryNode<AnyType>(x);
            else if(x.compareTo(t.element) < 0) {
                t.left = insert(x, t.left);
            else if(x.compareTo(t.element) > 0 ) {
                t.right = insert(x, t.right);
            else {
                throw new DuplicateItemException(x.toString());  // Duplicate
            return t;
         * Internal method to remove from a subtree.
         * @param x the item to remove.
         * @param t the node that roots the tree.
         * @return the new root.
         * @throws ItemNotFoundException if x is not found.
        protected BinaryNode<AnyType> remove(AnyType x, BinaryNode<AnyType> t)
            if(t == null) {
                throw new ItemNotFoundException(x.toString());
            if(x.compareTo(t.element) < 0) {
                t.left = remove(x,t.left);
            else if(x.compareTo(t.element) > 0) {
                t.right = remove(x, t.right);
            else if(t.left != null && t.right != null) // Two children
                t.element = findMin(t.right).element;
                t.right = removeMin(t.right);
            else {
                t = (t.left != null) ? t.left : t.right;
            return t;
         * Internal method to remove minimum item from a subtree.
         * @param t the node that roots the tree.
         * @return the new root.
         * @throws ItemNotFoundException if t is empty.
        protected BinaryNode<AnyType> removeMin(BinaryNode<AnyType> t)
            if(t == null) {
                throw new ItemNotFoundException();
            else if(t.left != null) {
                t.left = removeMin(t.left);
                return t;
            else {
                return t.right;
        * Given a non-empty binary search tree,
        * return the minimum data value found in that tree.
        * Note that the entire tree does not need to be searched.
        * @param t the node that roots the tree.
        * @return node containing the smallest item.
        protected BinaryNode<AnyType> findMin(BinaryNode<AnyType> t)
            if(t != null) {
                while(t.left != null) {
                    t = t.left;
            return t; //the smallest value
         * Internal method to find the largest item in a subtree.
         * @param t the node that roots the tree.
         * @return node containing the largest item.
        protected BinaryNode<AnyType> findMax(BinaryNode<AnyType> t)
            if(t != null) {
                while(t.right != null) {
                    t = t.right;
            return t; //the largest value
         * Internal method to find an item in a subtree.
         * @param x is item to search for.
         * @param t the node that roots the tree.
         * @return node containing the matched item.
        private BinaryNode<AnyType> find(AnyType x, BinaryNode<AnyType> t)
            while(t != null) {
                if(x.compareTo(t.element) < 0) {
                    t = t.left;
                else if(x.compareTo(t.element) > 0) {
                    t = t.right;
                else {
                    return t;    // Match
            return null;         // Not found
        public void betweenTraverse() {
         betweenTraverse(root);
        * Given two integers,
        * print all the values in the tree which are between these two numbers
        * in ascending order.
        * @param t is BinaryTree to search through
        * @param a is min integer to start print from
        * @param b is max integer to keep integer print between
        private void betweenTraverse(BinaryNode<AnyType> t)
         //enter samllest vaule
         int a = System.in.read();
         //enter largetest vaule
         int b = System.in.read();
         if (t != null) {
             inorderTraverse(t.left);
             if(t.elementAt(t) >a && t.elementAt(t) < b) { //LINE 274 with error
              System.out.println(t.elementAt(t));
             inorderTraverse(t.right);
        * Given an array of unsorted integers 
        * adds add the these elements of unsorted as nodes
        * to an initially empty binary search tree
        * @param x is array which it element to be added to a binary tree
        public BinarySearchTree<Integer> numberstoTree(int[] x)
         BinarySearchTree<Integer> treeOne = new BinarySearchTree<Integer>();
         Arrays.sort(x);
         for (int i = 0 ; i < x.length ; i++) {
                int j = x;
         treeOne.insert(j);     
         treeOne.inorderTraverse();
         return treeOne;
    public void inorderTraverse() {
         inorderTraverse(root);
    private void inorderTraverse(BinaryNode<AnyType> t) {
         if (t != null) {
         inorderTraverse(t.left);
         System.out.println(t.elementAt(t));
         inorderTraverse(t.right);
    // Test program
    public static void main(String[] args)
    BinarySearchTree<Integer> t = new BinarySearchTree<Integer>();
    final int NUMS = 4000;
    final int GAP = 37;
    System.out.println("Checking... (no more output means success)");
    for( int i = GAP; i != 0; i = ( i + GAP ) % NUMS ) {
    t.insert(i);
    for(int i = 1; i < NUMS; i += 2) {
    t.remove(i);
    if(t.findMin().elementAt(t) != 2 || t.findMax().elementAt(t) != NUMS - 2) { //LINE 332 with error
    System.out.println("FindMin or FindMax error!");
    for(int i = 2; i < NUMS; i += 2) {
         if( t.find(i) != i) {
    System.out.println("Find error1!");
    for(int i = 1; i < NUMS; i += 2) {
    if(t.find(i) != null) {
    System.out.println("Find error2!");
    }I getting these errors:BinarySearchTree.java:274: operator > cannot be applied to java.lang.Comparable,int
         if(t.elementAt(t) >a && t.elementAt(t) < b) {
    ^
    BinarySearchTree.java:274: operator < cannot be applied to java.lang.Comparable,int
         if(t.elementAt(t) >a && t.elementAt(t) < b) {
    ^
    BinarySearchTree.java:332: elementAt(BinaryNode) in BinarySearchTree cannot be applied to (BinarySearchTree<java.lang.Integer>)
    if(t.findMin().elementAt(t) != 2 || t.findMax().elementAt(t) != NUMS - 2) {
    ^
    BinarySearchTree.java:332: cannot find symbol
    symbol : method elementAt(BinarySearchTree<java.lang.Integer>)
    location: class java.lang.Integer
    if(t.findMin().elementAt(t) != 2 || t.findMax().elementAt(t) != NUMS - 2) {
    ^ I've tried to change the method return types, to integer, AnyType but still producing more or same amount of errors, any help debugging this would be so helpful!.
    Thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    So i've tried to re implement the static statements. i.e
    if(t.findMin().compareTo(t.elementAt(t.root)) != 2 || t.findMax().compareTo(t.elementAt(t.root)) != NUMS - 2) {
                System.out.println("FindMin or FindMax error!");
         }but now receiving this error :
    BinarySearchTree.java: operator > cannot be applied to java.lang.Comparable,java.lang.Integer
             if(t.elementAt(t) > A && t.elementAt(t) < B) { //LINE 274 WITH ERROR
                                  ^
    BinarySearchTree.java: operator < cannot be applied to java.lang.Comparable,java.lang.Integer
             if(t.elementAt(t) > A && t.elementAt(t) < B) { //LINE 274 WITH ERROR
                                                        ^
    BinarySearchTree.java: cannot find symbol
    symbol  : method compareTo(java.lang.Integer)
    location: class BinaryNode<java.lang.Integer>
            if(t.findMin().compareTo(t.elementAt(t.root)) != 2 || t.findMax().compareTo(t.elementAt(t.root)) != NUMS - 2) {
                        ^
    BinarySearchTree.java: cannot find symbol
    symbol  : method compareTo(java.lang.Integer)
    location: class BinaryNode<java.lang.Integer>
            if(t.findMin().compareTo(t.elementAt(t.root)) != 2 || t.findMax().compareTo(t.elementAt(t.root)) != NUMS - 2) {The method compareTo takes an object as defined in the comparable interface which my BinarySearchTree extends. Binary Node is a child of BinarySearchTree. I've been messing around with where i initiate the compareTo method but not had any success, any idea/push in the right direction would be appreciated.
    Thanks

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

  • Binary Search assumption

    Suppose the following instance of the binary search:
    BINARY-SEARCH(A,key,left,right)
    if left = right
    then return left
    else mid= (left + right)/2
    if key < A[mid]
    then return BINARY-SEARCH(A,key,left,mid &#8722;1)
    else return BINARY-SEARCH(A,key,mid,right)Assume that a binary search for key1 in A (even though A is not sorted) returns slot i. Similarly, a binary search for key2 in A returns slot j. Explain why the following fact is true: if i < j, then key1 <= key2.
    My question is that i'm not convinced that key1 can be key2 and my justification is as follows:
    1) If the array is even unsorted then if even we have two elements in the target array having the same values(key1=key2) then the output will be the same i.e. on searching for a specific key in a sorted or unsorted array then it will return a specific value for a specific key and so we can deal with the binary search as a function whose domain is the domain of the values of array and the range is the range[1-LENGTH[A]].
    2) And so the assumption : if (f(key1)<f(key2)) can only holds if key1 not equal to key2 because from the definition of the function we can't have two values for the specific function.
    Edited by: cybermask on Feb 2, 2009 4:38 AM

    The value ultimately returned by this function is a value that sits between left and right.
    Every time you compare the key with the value sitting at mid, you either take the left branch which will ultimately lead to a value less than mid, or you take the right branch which will lead to a value greater than or equal to mid.
    If you stuff two different keys into this routine, one could expect that there will be some initial portion where the paths were in agreement, i.e. where they compared to the value at mid, got the same result and took the same branch, and then there will be that first branch where they did not take the same path. (of course either of these path portions could be null. Possibly there was NO initial portion on which they agreed, and possibly for different keys, they agreed on every single comparison and you ended up on the same value.)
    However, in the general case, at the moment that they did not take the same branch, one key was less than A[mid] and the other was not. The key that was less than that A[mid] ended up with a value i that was less than mid, and the other ended up with a value that was mid or greater.
    So if i < j it means that at some point key1 < some A[mid] <= key2
    You are right, that the equality won't happen but that doesn't mean that the statement as given is false, it just means that it could be given a tighter bound.
    i.e. if it is true that i<j implies key1<key2 then it is also true that i<j implies key1<=key2

Maybe you are looking for