Binary search in List of Lists

Hi,
I have List of Lists (i.e an List of ArrayList within ArrayList), now i have being trying to do use binarySeach using the comparator api in Collections framework .. but no luck . Can someone help me out
thanx
sharad

Yes i have the listed sorted using the sort api on collections framework... following is the piece of code which sorts the String numbers stored in List of Lists. (please note the following code has been modified from its original source, so that i can post it across forums). Now using the binarysearch api in Collection framework .. i need to search for string say 5401880000 .. can i do it.
import java.util.*;
public class MySort
     public static void main(String args[])
          List innerList = new ArrayList();
          List outerList = new ArrayList();
          innerList.add(new String("5889319999"));
          innerList.add(new String("5889310000"));
          outerList.add(innerList);
          innerList = new ArrayList();
          innerList.add(new String("5401880000"));
          innerList.add(new String("5401889999"));
          outerList.add(innerList);
          innerList = new ArrayList();
          innerList.add(new String("5425550999"));
          innerList.add(new String("5425550000"));
          outerList.add(innerList);
          System.out.println ("unsorted list ---> "+outerList);
// sorting the collections ...
          Collections.sort(outerList, new Comparator()
          public int compare(Object o1, Object o2)
          List list1 = (List) o1;
          List list2 = (List) o2;
          String d1 = (String) list1.get(0);
          String d2 = (String) list2.get(0);
          return d1.compareTo(d2);
          System.out.println("Sorted: " + outerList);

Similar Messages

  • How to "quick search" in a sorted list ?

    Hi all,
    I need that your advice to choose the best collection to modelize my data.
    Let me describe you the context of my problem:
    I work on an antenna pattern file which looks like this:
    Elevation (deg);Gain (dB)
    0;5
    3;45
    6;3.1
    10;6.5
    16;18.1
    20;33.1
    24;31.2
    30;3.5 I need, for a given elevation angle, to get the related gain. if the exact value of the angle is not found, we will return the gain of the nearest angle.
    For example:
    If the elevation angle is 5 degrees, I must return 3.1 dB.This operation should be called a big number of time (about many hundred calls)
    What are your advices to modelize my data ? What is the best collection to do it ? What is the best way to quick search in this data to get the gain realted to a given angle ?
    I though to use the binary search tree. What do you think about this solution ? Do you known of the Java API contains an implementation of the binary search trees ?
    I though too to use an hashset. The hashcode should be computed in order to access to the nearest angle in the list of values. But I did not find the alogrithm to compute a such hash code. Maybe it is a wrong way.
    Please, help me.
    Tell me your opinion and your advices to solve my problem.
    Let me know if you need more information
    Thanks

    OK, it works.
    I created a class for my data:public class ElGainPatternElement
      private double elevation;
      private double gain;
    +getters/setters
    }Then, I created a comparator to compare my elements on the elevation attribute.
    Finally, I specialiazed the Collections.binarySearch method in order to return the value instead of the index.
    I the object is not found, I return the inferior (or superior) object.
    public static <T> T binarySearch(List<? extends T> list, T key,
          Comparator<? super T> c, boolean isMinStrategy)
        int index = Collections.binarySearch(list, key, c);
        // si objet non trouv�
        if (index < 0)
          // r�cup�rer l'index le plus proche de celui recherch�
          index = isMinStrategy ? (-index - 2) : (-index - 1);
          // si plus grand que tous les �lts, retourner le dernier de la liste
          if (index >= list.size())
            index = list.size() - 1;
          // si plus grand que tous les �lts, retourner le premier de la liste
          else if (index < 0)
            index = 0;
        // retourner l'objet le plus proche au regard de la strat�gie
        return list.get(index);
      }It works very well.
    But now, I need to change the strategy to use if the wanted elevation is not in the list.
    If you look at the example of my first post, the 5 degrees of elevation is not in my list. So, I have to interpolate the values of the gain in order to get a correct gain.
    If possible, it should use the least squares interpolation (I'm not sure of my traduction of "moindres carr�s").
    I have really no idea of the way to do it.
    Can anyone help me with this interpolation ? I have never use algorithm of interpolation (except the mean of 2 values).
    Maybe the Java API provides some utilities that can help me to interpolate my values ... any suggestions ?
    Thanks

  • When searching the calendar in list view, appointments erlier than a few years could not be found after search. en appointment from 1974 could not be found although it appears in the list.

    When searching the calendar in list view, en appointmet erlier than a few years could not be find although the appointmet is listed in the List wiew ???,
    An appointment from 1974 could not be found, in SEARCH MODE, although it appears in the calendar.

    Pardon me for a moment while I (politely) rant in your general direction...
    This type of response is not just unhelpful—it is the antithesis of helpful.
    This is a support forum. Its purpose is helping to resolve people's problems. Sometimes those problems are going to require long explanations or lots of information. That either comes out in the original post or over the course of several back-and-forth replies; the former produces long posts but takes less time overall than the latter.
    If you don't have the patience to read through a long post, then just move on. Posting a "too long, didn't read" comment adds nothing beneficial to anyone. All it does is reveal that the person who made that comment thinks it's important to tell everyone that their attention span is too short for anything longer than a tweet.
    Yes, my post was long. Had you read it, you might have understood why it's so long. I'm trying to provide information that people searching these forums about this problem might find helpful. I did this because when I searched for info on this problem, I found lots of people with a similar problem, but no answers that went beyond "restore from backup". Since that advice wasn't the solution for me, I decided that more information might prompt someone with more knowledge and access than I have to investigate. Since you couldn't be bothered to read it, you clearly aren't the kind of person whose attention I was hoping to catch.
    Certainly I could have made the post shorter, but I think putting it into a narrative like this makes it easier to follow and provides a context that a terse recitation of bare facts does not. If you disagree, that's your prerogative, but please don't waste everyone else's time by posting a comment just to say that you didn't read it.
    I find it appalling that someone who's able to reach Level 6 on these support forums would post a "tldr" comment. That does not reflect positively on you or these forums.
    End of rant.

  • When usung google search I get a listing but when I click on it gets replace with spam

    When usung google search I get a listing but when I click on a link it gets replace with spam. I notice a half blue spiral in front of the link that pops up.
    == This happened ==
    Every time Firefox opened
    == every time I use use the Google Search in firefox

    This seems to be going around. I haven't studied it in detail, but here is an example of a removal guide:
    http://malwaretips.com/blogs/trovi-com-removal/
    ''There are many other removal guide sites, but often they are designed to confuse you so you purchase paid support services. Most likely you won't need to do that in this case.''
    Please also see our support article on cleaning up malware, and the specialized forums listed toward the end: [[Troubleshoot Firefox issues caused by malware]].
    In the short run, assuming an extension is to blame, you may want to use Firefox in its Safe Mode. That's a standard diagnostic tool to deactivate extensions and some advanced features of Firefox. More info: [[Troubleshoot Firefox issues using Safe Mode]].
    You can restart Firefox in Safe Mode using either:
    * "3-bar" menu button > "?" button > Restart with Add-ons Disabled
    * Help menu > Restart with Add-ons Disabled
    Not all add-ons are disabled: Flash and other plugins still run
    After Firefox shuts down, a small dialog should appear. Click "Start in Safe Mode" (''not'' Reset).

  • Formatted Search inside a Price List

    Hi,
    Is it possible to put a formatted search inside a Price List which will auto-update?
    I created a query which looks at Special Prices tables OSPP and put an FMS in Price List 10. However, this FMS does not auto-update - it only updates when I click the "magnifying glass" of the formatted search. It would be cumbersome to click all items one-by-one.
    Thanks,
    Ajay Audich

    Hi...
    I understand that your formatted search is applied to the price column in your list of Charges 10. You've proven that their execution is made when leaving the modified column "Manual"? ..
    This column can fill it with one and then clicking on the column header.
    Best regards,

  • Searching only a particular list or library

    Just completed an upgrade from WSS 3 to 2013 Foundation.  All went well, but overlooked in our testing was that it seems users can no longer only search within the particular document library they are in.
    We have a couple knowledge base sites that share the same level of a site collection and each KB is its own document library.  Users are having difficulty locating the documents they need as they are returning results from all of the KBs rather than
    the one they are in.
    Short of creating a subsite for each knowledge base, is there a way to enable the search "drop-down" to only enable search in a given list or library as they were able to do in WSS.  I have verified that the document library web part has "show
    search box" enabled, but that seems to be a phantom setting for foundation ?  Or any other work-arounds people have found?

    Hi,
    For only returing office files, you can try to set the query string like:
    (FileExtension:doc OR FileExtension:docx OR FileExtension:xls OR FileExtension:xlsx OR FileExtension:ppt OR FileExtension:pptx OR FileExtension:pdf) (IsDocument:"True" OR contentclass:"STS_ListItem")
    For the URL, if you hover it, by default, it show the entire URL of the library/list. If you want to show the Title of the library/list, you need to customize the display template.
    Here is a post about customizing display template to show site collection title, please check if it is useful for you:
    http://sharepoint.stackexchange.com/questions/93492/managed-crawled-property-for-site-collection-title
    Best Regards,
    Wendy
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected]

  • Can I Change SEARCH to default as LIST view rather than GROUPS view?

    Can I Change SEARCH to default as LIST view rather than GROUPS view?
    I always end up doing a command+2 and if I can default this it would be better.
    THANKS

    Perform a search, click on the List View icon in the Finder window's toolbar, press COMMAND-J to open the View Options dialog, check the box labeled "Always open in list view."

  • In numbers 2 there was a "show search" which gave a list of all occurences of a value with the location. Does this exist in Numbers 3?

    in numbers 2 there was a "show search" which gave a list of all occurrences of a value with the location. Does this exist in Numbers 3?

    G.,
    The search results pane is gone in V3. If it's critical, stay in V2. I'm not being flippant, I have certain documents that I very carefully keep away from V3 because I don't want to give up the V2 features for those particular files. Some users have reported problems with having both versions active at the same time, so it's best to quit one before launching the other, but other than that you just need to be careful not to open your V2 documents with V3.
    Jerry

  • Why is 'Qlixter' Social Search not in the list of search engines?

    Why is 'Qlixter' Social Search not in the list of search engines? Its a superb social search engine and would be of great benefit to all Firefox users. Am a little dissapointed that it is not on the selection dropdown. Would it be possible to have this included and if so how do I go about it?
    Thank you for your help and support.
    Kind Regards
    Leslie
    == This happened ==
    Every time Firefox opened
    == Since its launch late last year

    You can add any search engine you wish -> instructions at [https://support.mozilla.com/en-US/kb/Search+bar#Managing_search_engines]

  • Speed of Searching lots of contact lists

    I would like to buy a Nokia phone 6110 N in Taiwan. However, some reasons make me hesitated.
    One is the compatibility of Nokia with my MS Outlook. I depend the Outlook software deeply when arranging my Calendar and handling my thousands contact lists. I am worried the compatibility of Nokia and MS Outlook on those functions.
    The second is the searching speed of contact lists in Nokia phone, specially with thousands items. Because I heard if the number of contact lists was more than one thousand, its speed would be very slow. Was it right?
    Can someone kindly give me an answer?

    Hello,
    For your first problem, you should always check out the phone's features before purchasing. Make sure MS Outlook is compatible.
    For you second problem, the more contacts you have the slower it will become when going through the contact list. This has always been an issue.

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

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

  • Binary Search

    Hi SDN Experts
    Is it must to use a sort statement before we use a binary search in a read statement. because in some cases its failing as SY-SUBRC = 4 if my internal table is not sorted.
    Please confirm me
    Regards
    Pratyusha

    Hi,
    Yes, it is mandatory to sort the table before doing a binary search.
    The principle of binary search only work in case of sorted tables.
    A binary search algorithm is a technique for finding a particular value in a sorted list. A binary search finds the median element in a list, compares its value to the one you are searching for, and determines if it’s greater than, less than, or equal to the one you want. A guess that turns out to be too high becomes the new top of the list, and one too low the new bottom of the list. The binary search's next guess is halfway between the new list's top and bottom. Pursuing this strategy iteratively, it narrows the search by a factor 2 each time, and finds your value. A binary search is an example of a divide and conquer algorithm.
    More on binary search.
    The idea is to eliminate half of the search space with each comparison.
    First, the middle element of the sequence is compared to the value we are searching for. If this element matches the value we are searching for, we are done. If, however, the middle element is “less than” the value we are chosen for (as specified by the relation used to specify a total order over the set of elements), then we know that, if the value exists in the sequence, it must exist somewhere after the middle element. Therefore we can eliminate the first half of the sequence from our search and simply repeat the search in the exact same manner on the remaining half of the sequence. If, however, the value we are searching for comes before the middle element, then we repeat the search on the first half of the sequence.
    Hope this helps.
    Regards,
    Kate

Maybe you are looking for

  • Error importing a RAW file

    When I try to import RAW files on my Canon T2i into iPhoto 08, I get an error message that says the import failed and the file is unreadable

  • How to resolve ORA-00205

    Hi, I tried to move the control file on the same drive i am getting this error. please find below steps and kindly suggest me a solution. SQL*Plus: Release 10.2.0.1.0 - Production on Thu Jul 10 08:16:14 2008 Copyright (c) 1982, 2005, Oracle. All righ

  • SRGB vs. Adobe (1998) RGB

    This is likely a basic question for all the pros out there, but here it is: In Scott Kelby's The Photoshop CS Book (2003), it says on p. 116: "Photoshops' default color space (sRGB...) is arguably the worst possible color space for professional photo

  • DDl and DMl's

    Hi All, Is their any way to find the current transaction(dml or ddl) happening database with helps any view if answer yes please send me the query Thanks Much, Napi.

  • Project Profile CPR001 (cProjects)

    Hi, We are on PPM5.0, working with cProjects-PS integration. Understand that the PS Profile for integration is CPR001. How can we define another profile that links with cProjects? Business requirement is to have a different profile. Please advise.