Sequential vs binary search

hello:
i am trying to know how to find the theoretical running time for both the sequential and binary search algorithms. i have written a program that determines the timing when running on my pc, however, i would like to compare these results against the ones ran via the program i have written.
thanks for any tips,
java40

I'm not sure what you're asking either.
It sounds like you're asking how to determine the time required to run the search. You can't determine that precisely. What you can do is determine the "big O" time, which doesn't tell you how fast it will run for a given input set, but does give you an idea of how fast the running time grows as the input size grows.
As for how you determine the big-O time, as already mentioned, that's well documented in textbooks, google, wikipedia...

Similar Messages

  • Linear search and binary search

    Hi
    can any one tell me what is linear and binary search in detail.
    and what is the difference between them .
    which one is useful in coding.
    Thanks&Regards,
    S.GangiReddy.

    hi,
    If you read entries from standard tables using a key other than the default key, you can use a binary search instead of the normal linear search. To do this, include the addition BINARY SEARCH in the corresponding READ statements.
    READ TABLE <itab> WITH KEY <k1> = <f1>... <kn> = <fn> <result>  BINARY SEARCH.
    The standard table must be sorted in ascending order by the specified search key. The BINARY SEARCH addition means that you can access an entry in a standard table by its key as quickly as you would be able to in a sorted table.
    REPORT demo_int_tables_read_index_bin.
    DATA: BEGIN OF line,
            col1 TYPE i,
            col2 TYPE i,
          END OF line.
    DATA itab LIKE STANDARD TABLE OF line.
    DO 4 TIMES.
      line-col1 = sy-index.
      line-col2 = sy-index ** 2.
      APPEND line TO itab.
    ENDDO.
    SORT itab BY col2.
    READ TABLE itab WITH KEY col2 = 16 INTO line BINARY SEARCH.
    WRITE: 'SY-SUBRC =', sy-subrc.
    The output is:
    SY-SUBRC =    0
    The program fills a standard table with a list of square numbers and sorts them into ascending order by field COL2. The READ statement uses a binary search to look for and find the line in the table where COL2 has the value 16.
    Linear search use sequential search means each and every reord will be searched to find. so it is slow.
    Binary search uses logrim for searching. Itab MUST be sorted on KEY fields fro binary search. so it is very fast.
    The search takes place as follows for the individual table types :
    standard tables are subject to a linear search. If the addition BINARY SEARCH is specified, the search is binary instead of linear. This considerably reduces the runtime of the search for larger tables (from approximately 100 entries upwards). For the binary search, the table must be sorted by the specified search key in ascending order. Otherwise the search will not find the correct row.
    sorted tables are subject to a binary search if the specified search key is or includes a starting field of the table key. Otherwise it is linear. The addition BINARY SEARCH can be specified for sorted tables, but has no effect.
    For hashed tables, the hash algorithm is used if the specified search key includes the table key. Otherwise the search is linear. The addition BINARY SEARCH is not permitted for hashed tables.
    Binary search must be preffered over linear sarch.
    Hope this is helpful, Do reward.

  • How does sy-tabix affect by binary search transforming no fields?

    1 report ztx1110.
         2 data: begin of it occurs 3,
         3           f1(2) type n,
         4           f2    type i,
         5           f3(2) type c,
         6           f4    type p,
         7           end of it.
         8
         9   it-f1 = '40'. it-f3 = 'DD'. it-f2 = it-f4 = 4. append it.
        10  it-f1 = '20'. it-f3 = 'BB'. it-f2 = it-f4 = 2. append it.
        11
        12 sort it by f1.
        13 do 5 times.
        14     it-f1 = sy-index * 10.
        15     it-f3 = 'XX'.
        16     it-f2 = it-f4 = sy-index.
        17     read table it
        18         with key f1 = it-f1
        19         binary search
        20         transporting no fields.
        21     if sy-subrc <> 0.
        22         insert it index sy-tabix.
        23         endif.
        24     enddo.
        25
        26 loop at it.
        27     write: / it-f1, it-f2, it-f3, it-f4.
        28     endloop.
    in this program changing value of sy-tabix as such sy-index.
    means in it's first loop it's value is 1, on second loop it's 2, and so on up to 5.
    okay that is due to binary search.
    but why binary search affecting this system variable?

    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

  • 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

  • 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

  • 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

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

  • Problem with Binary Search.

    Hi Gurus.
    I am using binary search to read data from internal table with approx more than 3lacs records. Also my table is sorted by BUKRS BELNR. But the problem is that i am getting records from lower half of table only and first half of table is ignoring, so i am not able to get all records. If i use nornal search, i am geting 7856 records and if i use binary search, i am geting only 1786 records....Can anyone help me why this is happening????

    Hi PV
    Actually my table contain line items. I am reading header data from bkpf for a single day. and for that document nos i am fetching line items. But if i use join or for all entries, i will get time exceed errror. so i get Period of that single day and taking data for that period from BSIS and then reading BKPF.. and only taking that line items for which document no in BKPF...
    my code is like
    SELECT-OPTIONS: cpudt FOR sy-datum DEFAULT '20030102'.
    SELECT bukrs belnr gjahr monat FROM bkpf
    INTO CORRESPONDING FIELDS OF TABLE ibkpf
    WHERE ( cpudt IN cpudt OR aedat IN cpudt ).
    ibkpf1[] = ibkpf[].
    SORT ibkpf1 BY monat.
    DELETE ADJACENT DUPLICATES FROM ibkpf1 COMPARING monat.
    IF ibkpf1[] IS NOT INITIAL.
      SELECT * FROM bsis INTO TABLE ibsis
          FOR ALL ENTRIES IN ibkpf1 WHERE gjahr = ibkpf1-gjahr
                                     AND monat = ibkpf1-monat.
      SORT ibsis BY bukrs belnr.
      LOOP AT ibsis.
        READ TABLE ibkpf WITH KEY bukrs = ibsis-bukrs
                                  belnr = ibsis-belnr
                                  BINARY SEARCH.
        IF sy-subrc NE 0.
          DELETE ibsis.
        ENDIF.
      ENDLOOP.
    ENDIF.

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

Maybe you are looking for

  • Issue in MC74 screen(SOP )

    Hi, We are using strategy 40 for a material-XYZ. We are trying to transfer the Planning data using MC74 to Demand management for the month of May,June,July etc for  this material- XYZ,we are getting error - "Requirement was already available". Infact

  • How do i know if my laptop has a built in mic, and how do i configure it?

    i have no audio when i try to skype.  The error msg says i need to check my mic how do i do that

  • Is Oracle Dropping Forms?

    Hello, I have been to several Oracle demos where the Oracle reps stated that forms is being dropped and all new development should be in Java (JDeveloper). But, Oracle has announced that Forms 10.x is going to be released. Does anyone know of any off

  • "Email Me" button in weird position.

    Hi there, I'm facing some troubles with the "Email Me" button position on a some of my pages but not all. When I do insert one, once my pages uploaded on my server (I don't use .Mac to host), sometimes it shows up exactly where I positioned it using

  • How to monitor 8i physical standby databases ?

    Hi guys, It seems easy to create and monitor standby databases for 9i and 10g instances through OEM 10, but what about 8i standby db ? Has everything to be done manually : creation, monitoring, maintenance ? It is at least possible to monitor redo tr