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

Similar Messages

  • Binary Search in Dynamic Read

    Here is the code
          read table <fs_it_crv> assigning <fs_wa_crv> with key
                                      ('objty') = wa_plfh-objty
                                      ('objid') = wa_plfh-objid
                                      binary search.
    If i use binary search system giving error while activating as
    You cannot use explicit or implicit index operations on tables with
    types "HASHED TABLE" or "ANY TABLE". "" has the type "ANY
    TABLE". It is possible that .
    How could i use Binary search in dynamic read

    Hello,
    how do you create your internal table "<FS_IT_CRV>" ?
    i found this thread [here|Need help regarding Dynamic Read Table statement;.
    You can try the code lines of  David Klotz.
    If you insert a sort statement before read and change read adding binary search it might work.
    SORT <gt_itab> BY (ge_key_field1) (ge_key_field2) (ge_key_field3) .
    * Finally, perform the search
      READ TABLE <gt_itab> ASSIGNING <gs_result>
              WITH KEY (ge_key_field1) = pa_cond1
                       (ge_key_field2) = pa_cond2
                       (ge_key_field3) = pa_cond3 BINARY SEARCH.
    I tried the following code in my own program and it works:
    SORT <wlf_t_data> BY (c_trkorr).
      read table <wlf_t_data> assigning <wlf_header> with key
             (c_trkorr) = 'DRR' binary search.
    Where   <wlf_t_data> is a dynamic table created by method create_dynamic_table of class cl_alv_table_create.
    Cordialement,
    Chaouki

  • Problem with Binary search statement

    Hi,
    I have problem with reading the internal with Binary search.
    I have two internal tables BSAS and BSIS. In BSAS I have 1,200,000 line items and BSIS 500,000 line items. I need to delete the line items if BSIS-BELNR NE BSAS-AUGBL.
    I am using the following code :
        LOOP AT gt_bsas .
          READ TABLE gt_bsis WITH KEY bukrs = gt_bsas-bukrs
                                      belnr = gt_bsas-augbl
                                      gjahr = gt_bsas-gjahr.
          IF sy-subrc NE 0.
            DELETE gt_bsas.
            CLEAR  gt_bsas.
          ELSE.
         endif.
    endloop.
    By this execution of the loop is taking long time. If I use the binary search it is fast but result is not correct.
    Please suggest me, how to resolve this issue.
    Thanks,
    Sri.

    Try this way:
    LOOP AT gt_bsas .
    <b>SORT GT_BSIS BY BUKRS BELNR GJAHR.</b>
    READ TABLE gt_bsis WITH KEY bukrs = gt_bsas-bukrs
    belnr = gt_bsas-augbl
    gjahr = gt_bsas-gjahr
    <b>BINARY SEARCH.</b>
    <b>IF sy-subrc eq 0.</b>
    ****Do Nothing.
    ELSE.
    <b>DELETE gt_bsas sy-tabix.</b>
    CLEAR gt_bsas.
    endif.
    endloop.
    1. Also make sure that the KEY mentioned in READ statement follows the same seqeunce of gt_bsis structure.
    Thanks,
    Santosh
    Message was edited by:
            SKJ

  • Need clarification to sum the entries in a internal table

    Hi Gurus ,
            Below i have written the logic for have the count of number of records in the internal table along with it i need to find the Total dollar amount of all the records .
    iam not sure how to have that total .
    please provide me the solution .
    you can see at the bottom the where i tryed to sum .
    LOOP AT IT_BKPF.
    *AP ENTRIES
        IF ( ( IT_bkpf-yke_awsys <> ' ' ) AND
                ( It_bkpf-ldgrp = '0L' OR It_bkpf-ldgrp = ' ' ) AND
                 ( IT_BKPF-BLART EQ 'N1' OR IT_BKPF-BLART EQ 'N2' OR IT_BKPF-BLART EQ 'LP' OR
                   IT_BKPF-BLART EQ 'TK' OR IT_BKPF-BLART EQ 'L5' OR IT_BKPF-BLART EQ 'L6' OR
                   IT_BKPF-BLART EQ '1A' OR IT_BKPF-BLART EQ '1B' OR IT_BKPF-BLART EQ '1C' OR
                   IT_BKPF-BLART EQ '1D' OR IT_BKPF-BLART EQ '1E' OR IT_BKPF-BLART EQ '1F' OR
                   IT_BKPF-BLART EQ '1G' OR IT_BKPF-BLART EQ '1H' OR IT_BKPF-BLART EQ '1I' OR
                   IT_BKPF-BLART EQ '1J' OR IT_BKPF-BLART EQ '1K' OR IT_BKPF-BLART EQ '1L' OR
                   IT_BKPF-BLART EQ '1M' OR IT_BKPF-BLART EQ '1N' ) ).
       CLEAR : COUNT_AP_0L ,V_COUNT_AP_0L.
          READ TABLE It_bseg WITH KEY BUKRS = IT_BKPF-BUKRS
                                      BELNR = IT_BKPF-BELNR
                                      GJAHR = IT_BKPF-GJAHR
                                      BINARY SEARCH.
          LOOP AT IT_BSEG FROM SY-TABIX.
            IF IT_BSEG-BUKRS <> IT_BKPF-BUKRS.
           OR IT_BSEG-BELNR <> IT_BKPF-BELNR
           OR IT_BSEG-GJAHR <> IT_BKPF-GJAHR.
              EXIT.
            ENDIF.
            IF SY-SUBRC IS INITIAL .
          COUNT_AP_0L = COUNT_AP_0L + 1.
          MOVE COUNT_AP_0L TO V_COUNT_AP_0L .
          AT END OF DMBTR.
          SUM.
          ENDAT.      ENDIF.
          ENDLOOP.
    Thanks ,
    vinay

    Hi,
    Use the sum statment after AT LAST.  statment.
    regards,
    Santosh Thorat.

  • Searching a binary search tree  written to a file

    hello
    I have a binary search tree which has 10 levels. Now I want to search a node
    after writing all the nodes to a file.
    Can anyone help me in doing this. A sample code would be great ...
    Thanks
    K

    You suggest that I do away with the inner class
    then?Absolutely. In fact I strongly suggest this. You are learning how to code and need to do things cleanly and in small steps. That means first creating your Node class and making sure it works. Then creating your Tree class, and making sure it works. In fact I would load the Strings into the Tree class first directly and testing things before even thinking about reading to and from files. Only then should you implement the file input and output steps.
    The key here is that you don't go on to the next step until you're reasonably sure that your current code works. Remember, it's MUCH easier to code than to debug.

  • Binary search tree - writing to a file in alphabetic order words from tree

    Hi
    I have written a program that will read a list of words from a file, insert these into a binary search tree, write words from the tree to another file, so that the resulting list contains words in ascending order. My input file Alpha1.txt contains the following contents in the order and format given (one word per line):
    Dawn
    Dave
    Mike
    Beth     
    David
    Gina
    Pat
    Cindy
    Sue
    My program is supposed to be producing an alphabetical list of these words in another file "final.txt".
    Instead it gives me the following list:
    Dave Beth David Gina Cindy Sue Pat Mike Dawn
    This is obviously wrong, right? My correct list in "final.txt" should be
    Beth Cindy Dave David Dawn Gina Mike Pat Sue
    I am not sure what is wrong with my code which I reproduce below:
    import java.io.*;
    import java.util.*;
    //read Java Developer's Almanac from exampledepot.com
    //Read this: http://en.wikipedia.org/wiki/Tree_traversal
    /**preorder(node)
      print node.value
      if node.left  ? null then preorder(node.left)
      if node.right ? null then preorder(node.right)
    public class AlphabeticBinarySortTree
         private static TreeNode root;
         private static TreeNode runner;
         static String[] alphaArray;
         static int alphaCounter;
         private static TreeNode alphaRunner;
         //Inner class
              private static class TreeNode
                   String word;
                   TreeNode left;
                   TreeNode right;
                   int count;
                   public TreeNode(String word)
                        this.word = word;
                        left = null;
                        right = null;
                   public void insertAll(TreeNode newNode)
                        if(newNode.word.compareTo(runner.word) < 1)
                             System.out.println("newNode.word = " + newNode.word);
                             if(runner.left == null)
                                  runner.left = newNode;
                                  runner = runner.left;
                             else
                                  insertAll(newNode);
                        else if(newNode.word.compareTo(runner.word) > 1)
                             System.out.println("newNode.word = " + newNode.word);
                             if(runner.right == null)
                                  runner.right = newNode;
                                  runner = runner.right;
                             else
                                  insertAll(newNode);
                        else
                             count++;
                   }// end method insertAll
                   // Recursively print words (with counts) in sorted order
                     public static void printInPreOrder(TreeNode root)
                             System.out.println(root.word + " ");
                             if(root.left != null)
                                   printInPreOrder(root.left);
                              if(root.right != null)
                                   printInPreOrder(root.right);
                       } //end method printInPreOrder()
                     //called from inside main
                    public static void arrangeInAscendingOrder(TreeNode root, PrintWriter pWriter)
                             if(root.left != null)
                                   arrangeInAscendingOrder(root.left, pWriter);
                             System.out.println();
                             System.out.println();
                             System.out.println(root.word + " ");
                             pWriter.write(root.word + " ");
                             if(root.right != null)
                                  arrangeInAscendingOrder(root.right, pWriter);
              }//end inner class TreeNode
         public AlphabeticBinarySortTree()
              root = null;
         //belong to the outer class
         public static void main(String[] args)
              System.out.println("This program reads text from a file that it will parse. ");
              System.out.println("In doing so, it will eliminate duplicate strings and ");
              System.out.println("pick up only unique strings.These strings will be in a ");
              System.out.println("stored in alphabetical order in a binary Search tree before they are ");
              System.out.println("written out to another text file in alphabetic order");
              //open the file for reading
              try
                   BufferedReader bReader = new BufferedReader(new FileReader("Alpha1.txt"));
                   String words;
                   int count;
                   //System.out.println("A test to inspect the contents of words: " + words);
                   //System.out.println("Words =" + words);
                   count = 0;
                   //why is there an endless loop when
                   //I use "while(str != null)
                   StringTokenizer st;
                   st = null;
                   //based on http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html
                   while ((words = bReader.readLine()) != null)
                        st = new StringTokenizer(words);
                       while(st.hasMoreTokens())
                            //shiffman.net/teaching/a2z/concordance
                            String token = st.nextToken();
                            System.out.println("Token = " +token);
                            AlphabeticBinarySortTree.initiateInsert(token);
                            //count the number of tokens in the string
                            count++;
                        }//end inner while
                   }//end outer while
                   System.out.println("Here are the contents of your tree:");
                   //System.out.println("before the call to print()");
                   print();
                   System.out.println("the no of words in the file is: " + count);
                   bReader.close();
              }//end of try
              catch(IOException exception)
                   exception.printStackTrace();
                   /**try
                             FileWriter fWriter = new FileWriter("final.txt");
                             BufferedWriter bWriter = new BufferedWriter(fWriter);
                             PrintWriter pWriter = new PrintWriter(bWriter);
                   catch(IOExcepion exception)
                        exception.printStackTrace();
         } // end main here
         //this method belongs to the outer class
         static void initiateInsert(String word)
              //TreeNode is also static by the way
              TreeNode newNode = new TreeNode(word);
              if(root == null)
                   root = newNode;
                   System.out.println("root.word = " + root.word);
                   runner = root;
              else
                   runner.insertAll(newNode);
         // Start the recursive traversing of the tree
            //without the access specifier 'static'
            //I would get the following error message
            //AlphabeticBinarySortTree.java:119: non-static method print() cannot be referenced from a static context
            public static void print()
                //System.out.println("**********AM I INSIDE THE PRINT() METHOD? ********");
               if (root != null)
                    //System.out.println("++++++++ AM I INSIDE THE IF BLOCK OF THE PRINT() METHOD? +++++++");
                    //System.out.println("Inside THE IF BLOCK OF print() BUT BEFORE THE CALL TO printInPreOrder(),root.word = " + root.word);
                  AlphabeticBinarySortTree.TreeNode.printInPreOrder(root);
                  //open the file for writing
                              try
                                             FileWriter fWriter = new FileWriter("final.txt");
                                             BufferedWriter bWriter = new BufferedWriter(fWriter);
                                             PrintWriter pWriter = new PrintWriter(bWriter);
                                             AlphabeticBinarySortTree.TreeNode.arrangeInAscendingOrder(root, pWriter);
                                          pWriter.close();
                              catch(IOException eException)
                                   eException.printStackTrace();
               }//end of if block
            } // end of method print
    }//end outer enclosing class here--------
    All help is highly appreciated. Thanks for your time and consideration.

    You suggest that I do away with the inner class
    then?Absolutely. In fact I strongly suggest this. You are learning how to code and need to do things cleanly and in small steps. That means first creating your Node class and making sure it works. Then creating your Tree class, and making sure it works. In fact I would load the Strings into the Tree class first directly and testing things before even thinking about reading to and from files. Only then should you implement the file input and output steps.
    The key here is that you don't go on to the next step until you're reasonably sure that your current code works. Remember, it's MUCH easier to code than to debug.

  • 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

  • Problem with binary search tree

    Hi all, just having troubles with a program im writing.
    My program is based on a binary search tree full of items which are passed in via an input file and then saved to an output file.
    I have written a sellItem method which gets passed in the item and quantity that has been sold which then needs to be changed in the binary tree.
    Here if my sell Item method:
        public void sellItem(Item item, int quantity){
            stockItem = item;
            mQuantity = quantity;
            if (tree.includes(stockItem)){
                int tempQuantity = stockItem.getQuantityInStock();
                tempQuantity -= mQuantity;
            else{
                throw new IllegalArgumentException("The Barcode " + mBarCode + " does NOT exist.");
        }and here is where i am calling it in a test class :
    number1.sellItem(item1, 40);Each item is in this format :
    ABCD, PENCIL, 1, 0.35, 200, 100, 200
    where 200 is the quantity.
    Therefore if i pass 40 into the method the binary search tree should then store the quantity as 160.
    below is a copy of my binary tree :
    public class BSTree extends Object {
        private class TreeNode extends Object{
            public Comparable data;
            public TreeNode left;
            public TreeNode right;
            public TreeNode() {
                this(null);
            public TreeNode(Comparable barCode){
                super();
                data = barCode;
                left = null;
                right = null;
        private TreeNode root; 
        private int nodeCount;
        public BSTree(){
            super();
            root = null;
            nodeCount = 0;
        public boolean isEmpty() {
          return root == null;
        public int size() {
          return nodeCount;
        private TreeNode attach(TreeNode newPointer, TreeNode pointer){
            if (pointer == null){
                nodeCount++;
                return newPointer;
            else {
                Comparable obj1 = (Comparable) newPointer.data;
                Comparable obj2 = (Comparable) pointer.data;
            if (obj1.compareTo(obj2) < 0) //Go left
                pointer.left = attach(newPointer, pointer.left);
            else //Go right
                pointer.right = attach(newPointer, pointer.right);
            return pointer;
        public void insert(Comparable item){
            //Create a new node and initialize
            TreeNode newPointer = new TreeNode(item);
            //Attach it to the tree
            root = attach(newPointer, root);
        public Comparable remove(Comparable key) {
            TreeNode pointer;
            TreeNode parent;
            //Find the node to be removed
            parent = null;
            pointer = root;
            while ((pointer != null) && !key.equals(pointer.data)) {
                parent = pointer;
                if (key.compareTo(pointer.data) <0)
                    pointer = pointer.left;
                else
                    pointer = pointer.right;
            if (pointer == null)
                return null;
            //Orphans
            TreeNode leftSubtree = pointer.left;
            TreeNode rightSubtree = pointer.right;
            if (parent == null)
                root = null;
            else if (key.compareTo(parent.data) < 0)
                parent.left = null;
            else
                parent.right = null;
            //Reattaching any orphans in the left subtree
            if (leftSubtree != null) {
                root = attach(leftSubtree, root);
                nodeCount--;
            //Reattaching any orphans in the right subtree
            if (rightSubtree != null) {
                root = attach(rightSubtree, root);
                nodeCount--;
            nodeCount--;
            return pointer.data;
        private TreeNode search(TreeNode pointer, Comparable key) {
            if (pointer == null)
                return null;
            else if (pointer.data.compareTo(key) == 0)
                return pointer;
            else if (key.compareTo(pointer.data) < 0)
                return search(pointer.left, key);
            else
                return search(pointer.right, key);
        public boolean includes(Comparable key) {
            return (search(root, key) != null);
        public Comparable retrieve(Comparable key) {
            TreeNode pointer;
            pointer = search(root, key);
            if (pointer == null)
                return null;
            else
                return pointer.data;
        public Comparable[] getAllInOrder() {
            Comparable[] list = new Comparable[nodeCount];
            inOrderVisit(root,list,0);
            return list;
        private int inOrderVisit(TreeNode pointer, Comparable[] list, int count) {
            if (pointer != null) {
                count = inOrderVisit(pointer.left, list, count);
                list[count++] = pointer.data;
                count = inOrderVisit(pointer.right, list, count);
            return count;
        public String toString() {
            StringBuffer result = new StringBuffer(100);
            inOrderString(root, result);
            return result.toString();
        private void inOrderString(TreeNode pointer, StringBuffer result) {
            if (pointer != null) {
                inOrderString(pointer.left, result);
                result.append(pointer.data.toString() + "\n");
                inOrderString(pointer.right, result);
    }Thanks for everyones help. Keep in mind i'm very new to java.

    Hi all, just having troubles with a program im writing.
    My program is based on a binary search tree full of items which are passed in via an input file and then saved to an output file.
    I have written a sellItem method which gets passed in the item and quantity that has been sold which then needs to be changed in the binary tree.
    Here if my sell Item method:
        public void sellItem(Item item, int quantity){
            stockItem = item;
            mQuantity = quantity;
            if (tree.includes(stockItem)){
                int tempQuantity = stockItem.getQuantityInStock();
                tempQuantity -= mQuantity;
            else{
                throw new IllegalArgumentException("The Barcode " + mBarCode + " does NOT exist.");
        }and here is where i am calling it in a test class :
    number1.sellItem(item1, 40);Each item is in this format :
    ABCD, PENCIL, 1, 0.35, 200, 100, 200
    where 200 is the quantity.
    Therefore if i pass 40 into the method the binary search tree should then store the quantity as 160.
    below is a copy of my binary tree :
    public class BSTree extends Object {
        private class TreeNode extends Object{
            public Comparable data;
            public TreeNode left;
            public TreeNode right;
            public TreeNode() {
                this(null);
            public TreeNode(Comparable barCode){
                super();
                data = barCode;
                left = null;
                right = null;
        private TreeNode root; 
        private int nodeCount;
        public BSTree(){
            super();
            root = null;
            nodeCount = 0;
        public boolean isEmpty() {
          return root == null;
        public int size() {
          return nodeCount;
        private TreeNode attach(TreeNode newPointer, TreeNode pointer){
            if (pointer == null){
                nodeCount++;
                return newPointer;
            else {
                Comparable obj1 = (Comparable) newPointer.data;
                Comparable obj2 = (Comparable) pointer.data;
            if (obj1.compareTo(obj2) < 0) //Go left
                pointer.left = attach(newPointer, pointer.left);
            else //Go right
                pointer.right = attach(newPointer, pointer.right);
            return pointer;
        public void insert(Comparable item){
            //Create a new node and initialize
            TreeNode newPointer = new TreeNode(item);
            //Attach it to the tree
            root = attach(newPointer, root);
        public Comparable remove(Comparable key) {
            TreeNode pointer;
            TreeNode parent;
            //Find the node to be removed
            parent = null;
            pointer = root;
            while ((pointer != null) && !key.equals(pointer.data)) {
                parent = pointer;
                if (key.compareTo(pointer.data) <0)
                    pointer = pointer.left;
                else
                    pointer = pointer.right;
            if (pointer == null)
                return null;
            //Orphans
            TreeNode leftSubtree = pointer.left;
            TreeNode rightSubtree = pointer.right;
            if (parent == null)
                root = null;
            else if (key.compareTo(parent.data) < 0)
                parent.left = null;
            else
                parent.right = null;
            //Reattaching any orphans in the left subtree
            if (leftSubtree != null) {
                root = attach(leftSubtree, root);
                nodeCount--;
            //Reattaching any orphans in the right subtree
            if (rightSubtree != null) {
                root = attach(rightSubtree, root);
                nodeCount--;
            nodeCount--;
            return pointer.data;
        private TreeNode search(TreeNode pointer, Comparable key) {
            if (pointer == null)
                return null;
            else if (pointer.data.compareTo(key) == 0)
                return pointer;
            else if (key.compareTo(pointer.data) < 0)
                return search(pointer.left, key);
            else
                return search(pointer.right, key);
        public boolean includes(Comparable key) {
            return (search(root, key) != null);
        public Comparable retrieve(Comparable key) {
            TreeNode pointer;
            pointer = search(root, key);
            if (pointer == null)
                return null;
            else
                return pointer.data;
        public Comparable[] getAllInOrder() {
            Comparable[] list = new Comparable[nodeCount];
            inOrderVisit(root,list,0);
            return list;
        private int inOrderVisit(TreeNode pointer, Comparable[] list, int count) {
            if (pointer != null) {
                count = inOrderVisit(pointer.left, list, count);
                list[count++] = pointer.data;
                count = inOrderVisit(pointer.right, list, count);
            return count;
        public String toString() {
            StringBuffer result = new StringBuffer(100);
            inOrderString(root, result);
            return result.toString();
        private void inOrderString(TreeNode pointer, StringBuffer result) {
            if (pointer != null) {
                inOrderString(pointer.left, result);
                result.append(pointer.data.toString() + "\n");
                inOrderString(pointer.right, result);
    }Thanks for everyones help. Keep in mind i'm very new to java.

  • 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 text files

    Hi all,
    I'm thinking about how to implement a binary sort to get,given a key, a value from a text file with a list of words in order. I saw randomaccessfile for j2se and I know that this work it's usually done by seek functions but how to do the seek work without the File class , with only the InputStream and Reader? I'm talking about the j2me midp 2 cldc 1.1 api, is there some methods or class to use for this thing? How could be implemented a binary search in a text file resident in the /res dir or the JAR or which could be the problems that cannot make possible this staff? If there was something like seek one way could be that one of decide a common length of words to read so going to the half of the text file it's possible with simply multiplication, and the do the binary search things.But for now I haven't found any resources or help.
    I hope you can help me to understand, thank you

    Hallo all,
    it is NOT the problem to locate the text I need to find in the fmb, or fmx.
    The problem is that since I want to change not only the text but also some more code around I want to do this in Form Builder - Object Navigator. And I'm not able to discover in which trigger or procedure the text appears.
    I do not want to edit fmx, or fmb in a text editor because I suupose theer are some checksums hidden for the format.
    -duro
    BTW in FMT there is no code seen (only some binary) for v6i as it was in v4.5.

  • 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

    Hello,
    I'm working on a BinarySearchTree and I am looking for a little bit of advice for my find method or overall optimization comments. For some reason when I set 'found' = null at the beginning of the method I am getting nullpointer exception. But, if I put it in the else statement, it never gets executed. As you can see, find is recursive function. Any help or advice would be greatly appreciated. Thanks in advance!!!!!
    * All items are ordered so that all items in the left subtree are smaller
    * than the item in the root and all items in the right subtree are larger
    * than the item in the root. This is true for all nodes in the tree.
    * No duplicates are allowed.
    * This tree is specific to the doctor's office application and therefore
    * contains Procedure objects - it is expected that Procedure objects are
    * comparable.
    public class BinarySearchTree {
         * The item stored in the root of this BinarySearchTree
        private Procedure value;
         * The parent of this BinarySearchTree
        private BinarySearchTree parent;
         * The left child of this BinarySearchTree
         return found;
         * Print the values of all the nodes of the BinarySearchTree rooted
         * at this node in infix order, one value per line.
        public void inOrder() {
             if ( leftChild != null ) {
                 leftChild.inOrder();
             System.out.println( value.toString() );
             if ( rightChild != null ) {
                 rightChild.inOrder();
    } // BinarySearchTree    */
        private BinarySearchTree leftChild;
         * The right child of this BinarySearchTree
        private BinarySearchTree rightChild;
         * A constructor used for the first node in the tree.
         * There is no parent.
         * @param item The value to be stored at this node of the tree.
        public BinarySearchTree( Procedure item ) {
           value = item;
           leftChild = null;
           rightChild = null; 
         * Accessor function for the value at this node
         * @return the value at this node.
        public Procedure getValue() {
            return value;
         * Accessor function for the parent of this node.
         * @return the parent of this node.
        public BinarySearchTree getParent() {
            return parent;
         * Accessor function for the left child of this node.
         * It allows me to move to the left child.
         * @return the left child of this node.
        public BinarySearchTree getLeftChild() {
            return leftChild;
         * Accessor function for the right child of this node.
         * It allows me to move to the right child.
         * @return the right child of this node.
        public BinarySearchTree getRightChild() {
            return rightChild;
         * Change the left child of this node.
         * @param newLeft the new left child
        private void setLeftChild( BinarySearchTree newLeft ) {
         return found;
         * Print the values of all the nodes of the BinarySearchTree rooted
         * at this node in infix order, one value per line.
        public void inOrder() {
             if ( leftChild != null ) {
                 leftChild.inOrder();
             System.out.println( value.toString() );
             if ( rightChild != null ) {
                 rightChild.inOrder();
    } // BinarySearchTree       leftChild = newLeft;
            leftChild.setParent( this );
         * Change the right child of this node.
         * @param newRight the new right child
        private void setRightChild( BinarySearchTree newRight ) {
            rightChild = newRight;
            rightChild.setParent( this );
         * Change the parent of this node.
         * @param newParent the new parent
         return found;
         * Print the values of all the nodes of the BinarySearchTree rooted
         * at this node in infix order, one value per line.
        public void inOrder() {
             if ( leftChild != null ) {
                 leftChild.inOrder();
             System.out.println( value.toString() );
             if ( rightChild != null ) {
                 rightChild.inOrder();
    } // BinarySearchTree
        private void setParent( BinarySearchTree newParent ) {
            parent = newParent;
         * Add a new item to the tree. If the item is smaller than
         * the value stored at the root node, find a place for it in
         * the left subtree.
         * @param item the item to be added to the tree.
        public void add( Procedure item ){
            BinarySearchTree curNode = this;
            if ( item.compareTo( value ) == 0 ) {
                System.err.println( "Can't have duplicate items in the tree" );
            } else if ( item.compareTo( value ) < 0 ) {
                if ( leftChild != null ) {
                    curNode = leftChild;
                    curNode.add( item );
                } else {
                    curNode.setLeftChild( new BinarySearchTree( item ) );
            } else if ( item.compareTo( value ) > 0 ) {
                if ( rightChild != null ) {
                    curNode = rightChild;
                    curNode.add( item );
                } else {
                    curNode.setRightChild( new BinarySearchTree( item ) );
         * Is the Procedure named in the parameter in the tree? Case is
         * ignored when doing the comparison. If the Procedure is found,
         * return it. If not, print a message and return null.
         * The purpose of the message is for you to KNOW that an item was
         * not found in the tree. Use the format:
         *     'item' not found in the binary search tree
         * where item is the name of the procedure that you are looking for.
         * @param  item The item to look for
        public Procedure find( String item ) {
         BinarySearchTree curNode = this;
         //???????blows up when I set it to null here
         Procedure found = null;
         if ( item.compareToIgnoreCase( value.getName() ) == 0 ) {
             found = value;
             System.out.println("**********************************"
                         + "***************************found it");
         else if ( item.compareToIgnoreCase( value.getName() ) < 0 ) {
                if ( leftChild != null ) {
              System.out.println("LLLLLLLLLLLLLLLLLLLLLLLLLLLLLL");
                    curNode = leftChild;
                    curNode.find( item );
            } else if ( item.compareToIgnoreCase( value.getName() ) > 0 ) {
                if ( rightChild != null ) {
              System.out.println("RRRRRRRRRRRRRRRRRRRRRRRRRRRRR");
                    curNode = rightChild;
                    curNode.find( item );
            //??????NEVER GETS EXECUTED WHEN I UNCOMMENT THIS OUT!!!
         //     else {
         //  found = null;
         //  System.err.println( item
         //          + "7777777777777777777777777777777777777777not found in the binary search tree");
         return found;
         * Print the values of all the nodes of the BinarySearchTree rooted
         * at this node in infix order, one value per line.
        public void inOrder() {
             if ( leftChild != null ) {
                 leftChild.inOrder();
             System.out.println( value.toString() );
             if ( rightChild != null ) {
                 rightChild.inOrder();
    } // BinarySearchTree

    For some reason when I set 'found' = null at the
    beginning of the method I am getting nullpointer
    exception.That must come from outside find() method since nothing in find() uses the value of the "found" variable.
    But, if I put it in the else statement, it never
    gets executed.That's because your if-else-else already considers all the possible cases -- the value that compareToIgnoreCase returns is either equal to, less than, or greater than 0. It can never be anything else.
    You only assign to the local variable "found" if the searched item was found immediately from the 'current node' (= the root); if the item was in the left or right subtree you are happily ignoring it. You needfound = curNode.find( item );in both of the else-cases.
    The item is "not found" when it should be in the left/right child by the comparison test, but the left/right child is empty. So the find() method needs this, and the same for the left childif (compare to > 0) {
        if ( rightChild != null ) {
            // find from child
        } else {
            // not found from tree at all
    }The "not found" code would have to be duplicated, so you should refactor the conditions...Here's a possibility:     if ( item is value ) {
                 // found it in the current node
            else if (item is less than value and leftChild is not null) {
                 // try to find it in the left child
            else if (item is greater than value and rightChild is not null) {
                  // try to find it in the right child
            else {
                  // should be in right/left child but
                  // it's empty --- not found!
            }

  • Significant Comparisons in Binary Search Trees?

    Hello,
    I am a bit confused as to what constitutes a significant comparison in a binary search tree. I have an assignment where I need to modify a BST class to keep track of the number of significant comparisons being done for an analysis of running time. The class supports search, insert, and delete and the assignment stipulates that each method needs to update the number of comparisons instance variable that you implement. The comparison count is obvious for the pure recursive search, but I don't understand what to and what not to count in the delete and insert methods. Is this a standard term that is defined explicitly, or is this my professor demanding of us to think critically for better or worse? Thanks for any help.

    I know what a BST tree is, and I know what comparisons are, but I
    don't know what 'significant comparisons' are. Maybe if you could tell
    me what the difference between a significant and insignificant
    comparison was I'd be in business.According to some notes on my desk, a 'significant comparison' causes
    a rotation of a subtreee in a 'red-black' tree; but I don't know what it is
    supposed to be in a general sorted binary tree. My guess is that this is
    not a generally accepted term. I might be wrong again ...
    kind regards,
    Jos
    ps. Hi Duffy, how are you doing?

  • 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

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

Maybe you are looking for

  • Help with Quality of Service (QoS)

    Hello all, I'm trying to set up QoS on my Actiontec MI424WR (Rev. I) router. I want to prioritze my Xbox One. I followed the guide linked below. http://support.actiontec.com/doc_files/MI424WR_Rev​._E&F_How_To_Configure_QoS.pdf When performing an Xbox

  • Used glitchey 24" imac intel

    just got a 24" Intel Core 2 duo(2006) off of ebay and everything was working fine and now the screen is getting all glitchey adn freezing up.  everything I have been reading says to run the Apple Hardware Test, but I don't hav the original discs that

  • Song modifications bug since iTunes 11.0.1

    Hello, Since I updated to iTunes 11.0.1 on Windows I have a very annoying bug, that didn't occur in the 11 version. When I am in the "Albums" viewing mode any modification to a song via the "Get Info" option doesn't appear before I click on a differe

  • When I try and send picture emails, they arrive as attachments.

    Hello there, I'm trying to send a newsletter-style email. I'd like it to arrive in all recipricants inbox's as a picture. When I drag and drop pictures into Mac Mail though, they arrive in Hotmail accounts (and probably others) as attachments rather

  • T420 Hinges second replacement in 1.5 years?

    My T420 Hinges are beginning to wobble again and not adequately support the screen. Basically any minor bump to the computer moves the screen back and forth. This makes it very difficult to use the machine in a car, bus, airplane, or on any surface o