Binary search question with objects

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

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

Similar Messages

  • 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 option with Read statement

    Hi,
    There are any chances that the Read statement with Binary search option to fail, even though the key exists??
    Here the itab is sorted in descending order. and then some duplicates are removed using the delete adjacent statement.
    Regards,
    Sandhip.

    Hi,
    Here is an example:
    sort itab1 by a b c.
    loop at itab2 into wa_itab2.
      read table itab1 into wa_itab1
                       with key a = wa_itab2-a
                                b = wa_itab2-b
                       c = wa_itab2-c
                           binary search.
      if sy-subrc = 0.
        wa_output-a = wa_itab1-a.
      endif.
    endloop.
    Another alternative is to use sorted tables.
    Hope it helps...
    P.S. Please award points if it helps...

  • Simple serialization question with objects

    Hi, I'm really new to the whole concept of serialization and what I want to do is create a blackjack game that can have up to 4 people playing, connected to a server that will act as the dealer. I need to be able to serialize some objects from the players to the server and have the server make some changes then send the objects back.
    However every example I've run across dealing with something of this nature involves writing to a file so I'm not sure what the code to do this would look like.
    My best guess would be ObjectInputStream and ObjectOutputStream but I don't understand how I can tell these streams that I just want to send the serialized object back and forth.
    If anyone could explain to me a bit better how these streams work, or show me roughly what the code might look like, I would really appreciate it.

    It doesn't matter whether you write to a file or a socket or a byte array or whatever. That stuff is what's under the ObjectOutputStream. When you create the OOS, you wrap it around some other stream (e.g. a FileOutputStream in the examples you're talking about I guess). To send something to a server, you'd instead just wrap it around the OutputStream of a Socket that's talking to that server. Everything else is the same.
    Whether you use raw sockets or some other means is up to you, but that's completely separate from the serialize/deserialize process.
    http://java.sun.com/docs/books/tutorial/essential/io/index.html
    http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

  • Question with object arrays..

    This is my code and it doesn't seem to be working properly
    public class familymember {
    public familymember(){
    Object[] array=new Object[500];
         public static void main(String args[]) {
         familymember array2 = new familymember();
         array2.array[51] = "500";
              System.out.println( array2.array[51]);
    I get the error message
    Error : No variable array defined in class familymember.
    familymember.java line 15 array2.array[51] = "500";
    What am i doing wrong?

    array cannot be accessed from outside it's block (in this case the constructor).
    just change your code this way:
    public class familymember {
      private Object[] array; // or public or protected or whatever you want
      public familymember(){
        array=new Object[500];
      public static void main(String args[]) {
        familymember array2 = new familymember();
        array2.array[51] = "500";
        System.out.println( array2.array[51]);
    }

  • "Binary search" in READ

    Hi frnds,
      I sumtyms  dont get the desired result while using the
    "BINARY SEARCH" addition with the "READ" statement.
    y is that? is there any rules to be followed to use binary search option in read statement.
    Regards,
    Madan...

    Hi
    Please go thru this.
    Binary Search in Standard Tables
    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 = <f> <result> BINARY SEARCH.
    and
    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.
    Example
    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.
    http://help.sap.com/saphelp_nw2004s/helpdata/en/fc/eb35f8358411d1829f0000e829fbfe/content.htm
    Thanks
    Shiva

  • Question about binary search tree

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

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

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

  • Basic binary search tree question

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

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

  • 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

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

  • READ statement with binary search

    Hi friends,
    I know that while using the READ statement that we have to sort data and use BINARY SEARCH  for faster search.
    I have a situation
    following are internal table contents
    belnr          agent    action
    9000001   name1    BRW
    9000001   name1    API
    when i use READ statement with where condition (  ( belnr - 9000001 ) and  ( action = 'BRW' ) )  with binary search then the SY_SUBRC value is 4.
    if i remove the binary search then its giving SY-SUBRC value 0.
    Can anybody explain why BINARY SEARCH fails.
    Points will be rewarded for correct answers.
    Thanks and regards,
    Murthy

    try this i am not getting sy-subrc 4
    TYPES:BEGIN OF TY_ITAB,
    BELNR TYPE BELNR,
    AGENT(30),
    ACTION(5),
    END OF TY_ITAB.
    DATA:IT_TAB TYPE TABLE OF TY_ITAB,
         WA_TAB TYPE TY_ITAB.
    WA_TAB-BELNR = 9000001.
    WA_TAB-AGENT = 'name1'.
    WA_TAB-ACTION = 'BRW'.
    APPEND WA_TAB TO IT_TAB.
    CLEAR WA_TAB.
    WA_TAB-BELNR = 9000002.
    WA_TAB-AGENT = 'name 2'.
    WA_TAB-ACTION = 'API'.
    APPEND WA_TAB TO IT_TAB.
    loop at it_tab into wa_tab.
    read table it_tab into wa_tab with key belnr = wa_tab-belnr  binary search .
    write: sy-subrc, wa_tab-agent.
    endloop.

  • Weird situation with BINARY SEARCH in READ statwment??

    Hi Experts,
    I got weird situation with BINARY SEARCH !! bcoz, below is my code,
    data: begin of it_vbap occurs o,
            vbeln like vbap-vbap,
            posnr like vbap-posnr, ( i also tried like, posnr(6) type n)
    end of it_vbap.
    data: counter type i ( i also tried like, counter(6) type n)
    my it_vbap is filled like below,
    vbeln----
    posnr
    12345678-------000001
    12345678-------000002
    12345678-------000003
    12345678-------000004
    12345678-------000005
    12345678-------000006
    sort it_vbap by posnr. (*)
    clear counter
    loop it_vbap.
    counter = counter + 1.
    read table it_vbap with key posnr = counter
    binary search (after commenting the above SORT * marked statement, then,if I delete BINARY SEARCH, then its working!!)
    if sy-subrc = 0.
    here is my logic.
    endif.
    endloop.
    so, now, for
    1st loop the sy-subrc = 0.
    2nd loop the sy-subrc = 0.
    3rdloop the sy-subrc NE  0.
    4th loop the sy-subrc = 0.
    5th loop the sy-subrc NE 0.
    6th loop the sy-subrc NE 0.
    so, why, ebven though there r all entires in it_vbap, why am getting the sy-subrc NE 0??
    Is the reason that, there r less number of entries in it_vbap?? and am using BINARY SEARCH??
    thanq
    Edited by: SAP ABAPer on Dec 4, 2008 8:33 PM
    Edited by: SAP ABAPer on Dec 4, 2008 8:37 PM
    Edited by: SAP ABAPer on Dec 4, 2008 8:37 PM

    Hello
    The following coding works perfect (6x sy-subrc = 0) on ERP 6.0:
    *& Report  ZUS_SDN_ITAB_BINARY_SEARCH
    REPORT  zus_sdn_itab_binary_search.
    TABLES: vbap.
    DATA: BEGIN OF it_vbap OCCURS 0,
    vbeln LIKE vbap-vbeln,
    posnr LIKE vbap-posnr, "( i also tried like, posnr(6) type n)
    END OF it_vbap.
    DATA: counter TYPE posnr.
    START-OF-SELECTION.
      " Fill itab with data:
    *  12345678-------000001
    *  12345678-------000002
    *  12345678-------000003
    *  12345678-------000004
    *  12345678-------000005
    *  12345678-------000006
      REFRESH: it_vbap.
      CLEAR: vbap.
      DO 6 TIMES.
        it_vbap-vbeln = '12345678'.
        it_vbap-posnr = syst-index.
        APPEND it_vbap.
      ENDDO.
      SORT it_vbap[] BY posnr.  " for BINARY SEARCH
      BREAK-POINT.
      clear counter.
      loop at it_vbap.
      counter = counter + 1.
      READ TABLE it_vbap WITH KEY posnr = counter
      BINARY SEARCH.  " (after commenting the above sort * marked statement, then,if i delete binary search, then its working!!)
      IF sy-subrc = 0.
        "here is my logic.
      ENDIF.
    ENDLOOP.
    END-OF-SELECTION.
    By the way, if your requirement is to check whether the first item has POSNR = '000001', the second item has POSNR = '000002' and so on then you can simplify your coding like this:
    counter = 0.
    LOOP AT it_vbap.
      counter = syst-tabix.
      IF ( it_vbap-posnr = counter ).
        " put in here your logic
      ENDIF.
    ENDLOOP.
    Regards
      Uwe

  • Java question help (applying binary search)

    please show me how do i apply a binary search inside this program where i can use the binary serach to search for the book author or book title
    // objectSort.java
    // demonstrates sorting objects (uses bubble sort)
    // to run this program: C>java libmainsys
    class libary
    private String booktitle;
    private String bookauthor;
    private String publisher;
    private int yearpublished;
    private int edition;
    private int nofcop;
    public libary(String title, String author, String pub, int yrpub, int edt, int nfcp)
    {                // constructor
    booktitle = title;
    bookauthor = author;
    publisher = pub;
    yearpublished = yrpub;
    edition = edt;
    nofcop = nfcp;
    public void displaylibary()
    System.out.print(" Book Title: " + booktitle);
    System.out.print(", Book Author: " + bookauthor);
    System.out.print(", Book Publisher: " + publisher);
    System.out.print(", Year Published: " + yearpublished);
    System.out.print(", Edition: " + edition);
    System.out.println(",No Of Copies : " + nofcop);
    public String getLast() // get title
    { return booktitle; }
    } // end class libary
    class ArrayInOb
    private libary[] nfcp; // ref to array ypub
    private int nElems; // number of data items
    public ArrayInOb(int max) // constructor
    nfcp = new libary[max]; // create the array
    nElems = 0; // no items yet
    // put libary into array
    public void insert(String title, String author, String pub, int yrpub, int edt, int nofcop)
    nfcp[nElems] = new libary(title, author, pub, yrpub, edt, nofcop);
    nElems++; // increment size
    public void display() // displays array contents
    for(int j=0; j<nElems; j++) // for each element,
    nfcp[j].displaylibary(); // display it
    System.out.println("");
    public void bubbleSort()
    int i, j;
    libary temp;
    for (i = nElems-1; i >= 0; i--)
    for (j = 1; j <= i; j++)
    if (nfcp[j-1].getLast().compareTo(nfcp[j].getLast())>0)
    temp = nfcp[j-1];
    nfcp[j-1] = nfcp[j];
    nfcp[j] = temp;
    } // end class ArrayInOb
    class libmainsys
    public static void main(String[] args)
    int maxSize = 1000; // array size
    ArrayInOb arr; // reference to array
    arr = new ArrayInOb(maxSize); // create the array
    arr.insert("Java_how__to_program", "Patty_John", "Deitel", 2001, 1, 430);
    arr.insert("System_Design", "Dexter_Smith", "Thomson", 2002, 3, 450);
    arr.insert("Program_Design", "Lorraine_Paul", "About", 1996, 2, 196);
    arr.insert("Computer_Architecture", "Paul_Andrew","Dzone", 2006, 5, 199);
    arr.insert("Visual_Basic_How_To_ Program", "Tom_Jones", "Jeffereson_publication", 2007, 4, 207);
    arr.insert("Information_ Management", "William_Peter", "Mcgraw_Hill", 1995, 3, 204);
    arr.insert("Sofware_ Application", "Henry_Sam", "Pearson", 2001, 6, 278);
    arr.insert("English", "Samantha_Julia", "James_Hill", 2005, 1, 200);
    arr.insert("Web_Publishing", "Audrey_Cynthia", "Surg", 2004, 3, 201);
    arr.insert("Human_Computer_Interaction", "Tony_Edward", "Telde", 2003, 3, 199);
    System.out.println("Before sorting:");
    arr.display(); // display items
    arr.bubbleSort(); // insertion-sort them
    System.out.println("After sorting:");
    arr.display(); // display them again
    } // end main()
    } // end class libmainsys

    I see you haven't worked out bubbleSort either. Since binary search only works on sorted arrays, I suggest you start there. Do you have the algorithms somewhere?
    If you really need to be able to search using either author or title, I suggest you create 2 Comparators that compare using the desired property. Comparator is just an interface that defines methods to compare 2 objects. You have to write your own implementation of it to compare library objects. You'll always have to sort and search using the same Comparator.

  • Hash Table/Binary Search Tree question

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

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

Maybe you are looking for

  • Infinity and MSN

    Has anyone come up with a definitive answer to why msn disconnects all the time when using BT Infinity?  i would love to know as it is really annoying me Andy

  • Home address not shown correctly

    Hello all,    I just got my first iPhone today, the iPhone 4s, very happy I am.    I also have an iPad 2 both have a similar issue.    In my contact card I have my home address as 84 Beaconhurst Drive Beacon Bay East London 5241 South Africa When I s

  • BI Publisher query

    when trying to convert the oracle report using the BIPBatchConversion utility. encountering the below error. Exception in thread "main" java.lang.NoClassDefFoundError: oracle/apps/xdo/rdfparser/BIPBatchConversion the below are the steps used. D:\Jdev

  • Photoshop scripts within Actions

    Ok so I am currently trying to run a photoshop script within an action specifically Image processor. I can include the script by importing menu item although evyerthing i run the action i have to set up the script aka choose folder locations etc. My

  • I have an older MBP that I purchased in 2006. I'd like to upgrade to Mountain Lion. Can this machine take that OS? Intel Core Duo running 10.6.8

    The issue is, I teach photography and just downloaded Lightroom 4. Well, LR4 won't run on the older OS. So, before I try to download Mountain Lion, I need to know if it will work on this computer or is it simply too old. Thanks