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

Similar Messages

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

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

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

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

  • Arrow key scrolling not working with advanced search- Adobe Reader X

    I'm using adobe reader X and when I get results from an advanced search I am scrolling down the search results with the arrow keys, but the document will not update. I know this will work. Can anybody please help?

    I am also having this problem.  Previous installations of Acrobat X allowed me to use the up and down arrows to navigate the search results, but no longer loads the appropriate page in the document.  I have to click each entry or hit the enter key after using the down arrows to update the page.

  • Weird situation with imessage (3 phones on same ID)

    My daughters & I all have iPhones (youngest has a 3Gs & oldest and myself 4G). I also have an iPad 2 (got it for Christmas 2011). All are running newest OS. Never have had a problem with iMessage before, until April 9 when my iPhone battery drained & it was super late and I was messaging my oldest to get home immediately....so I had to use my iPad 2 to continue texting her. Ever since I did this, we she & I message each other it does NOT alert us that we got a message, because it shows up as a blue message like we sent it to ourselves & my other daughter gets the message as well, like it came from her sister (even if it's a message I sent to the oldest).
    After this problem became apparent, I shut off my iPad 2 iMessenger. But the problem STILL is occuring. I have even turned off iMessage on my iPhone 4 & just texted for about a week. Then turned it back on & situation STILL is occuring.
    Please someone HELP us. I need to know that my girls got their messages. All of our devices are under the same Apple ID (could this be the problem?) & can we use different IDs, but still access all of our purchases (we have almost 500 apps on this ID & way more songs than that).

    It's more that likely the same ID's are causing the problem.  http://support.apple.com/kb/HT3529 
    Probably need to create a separate ID for your children.

  • Weird situation with MOVE-CORRESPONDING in standard SAP include!!

    Hello Experts,
    We have a standard_SAP_field_1 (attached to a standard_SAP_data_element_1) in standard_SAP_structure_1, but unfortunately its NOT there in KOMP structure!! Hence I added this standard_SAP_field_1 with in customer name space as 'ZZ_standard_SAP_field_1' by attaching the same standard_SAP_data_element_1.
    The standard_SAP_data_element_1 attributes are as CHAR, 2.
    Now, in one of the standard SAP include of VA42.....we have a statement as below,
    MOVE-CORRESPONDING standard_SAP_structure_1 TO komp.
    Then the value (say, AA) should transfer from standard_SAP_field_1 of standard_SAP_structure_1  to ZZ_standard_SAP_field_1 of KOMP, right? but, its not happening!! pls. let me know the reason and how to fix it?

    Okay...
    Field one is called: FIELD1
    Your own created field two is called ZZ_FIELD1.
    And now... MOVE-CORRESPONDING. Do a F1 on that and tell me: do the two fieldnames correspond?

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

  • Reg : Read statement using Binary Search....

    I have an Internal Table as below
    Value           Description
    100               Product
    2008             Production Year
    05                 Production Month
    I am using Read statement with Binary Search for getting Production Month.
    Read table itab with key Description = 'Production Month' binary search.
    I am getting sy-subrc as 4 eventhough data is present in the table for Production Month.
    What may be the problem.

    Hi suganya,
    use
    sort table itab ascending by <production month>.    
    Read table itab with key description = <production month> binary search.
    Remember always, while using binary search always sort the internal table.
    Regards,
    Sakthi.

  • Read table and binary search

    Hi all,
    I have a simple query regarding read int_tab with binary search.
    Why reading  internal table with binary search fails if it is sorted in descending order table must be sorted in ascending order?
    I check fo the algorithm of binary search, it does not talk about sort order. As far as my understanding goes binary search only require sorted table but while reading table in SAP it has to be sorted in ascending order!!

    By default binary search assumes that the sort order is ASCENDING.
    If you sort the list in descending and then try to binary search your quires will fail. Look at an example:
    Let the descending order internal table as:
    Field1      Field2
    Sam        50000
    John       34786
    Boob      54321
    Alice       12345
    When you do binary search with key = 'Sam' then it will directly go to 2nd and 3rd records for comparision. The binary search algorithm compares 'Sam' with 'John' and it concludes that 'Sam' is greater than 'John' and it will continue to look downward into the internal table. And when it reaches the end of the internal table then the value of SY-TABIX = 5 and SY-SUBRC = 8 (Key is greater than the all).
    And if you do binary search with key = 'Alice' then the binary search algorithm compares 'Alice' with 'John' and it concludes that 'Alice' is lower than 'John' and it will continue to look upward into the internal table. And when it reaches above the first record in internal table then the value of SY-TABIX = 1 and SY-SUBRC = 4 (points to the next largest entry).
    The only correct result you will get is when you execute statement with key='John' (In this particular case) . SY-TABIX = 2 and SY-SUBRC = 0. I think you got this binary search algorithm.

  • READ using Binary Search

    Hi,
    Is it necessary to use all the sorted keys in READ using BINARY SEARCH .
    For EX: Sort it_tab BY key1 key2
    While Reading i will use only key1 with BINARY SEARCH,Please tell me whether READ statement works?
    Thanks,
    Rathish

    Hello Ratish,
    There isnt any hard and fast rule that you will have to use all the fields on which you sort. The key fields which you may want to use in the READ statement depends on the logic with which you are reading the internal table. As Rob pointed out its better to use all the fields which could make a record unique in the READ statement else it would keep reading only the first occurence of the record.
    Vikranth

  • About binary search in standard table

    To improve the performance, we usually sort a standard table and do binary search when READ TABLE.
    Does this only work on key fields that are specified in the table definition.
    If I sort the table by a non-key field and do binary search, is it also helpful in performance improvement?

    Dear Ming,
    If you  sort the table by a non-key field and do binary search,
    it is also helpful to improve the performance.
    but You have to use same keys in read statement which you have used in sorting internal table.(k1, k2)
    Eg.
    SORT itab BY k1 k2.
    then you have to use same key in read statement other wise it returns wrong result.
    READ TABLE itab INTO wa_itab
    WITH KEY k1 = itab2-k1
                      k2 = itab2-k2
    BINARY SEARCH.
    Please find below more points:
    1. Don't forget to SORT internal table.
    2. Arrange the fields in WITH KEY same with sorting.
    3. Put SORT right before READ with BINARY SEARCH or before the loop stament to optimize
    Thanks,
    Vikas.

  • Can't we use Binary SEARCH  for TYPE SORTED TABLE?(Performance Improvement)

    Hi Expert!
                       I have declare a sorted type table with NON -UNIQUE, and want to use Binary search in read statement. But while  using bunary search in read statement I'm facing an error. The ERROR is
    "Table LI_MARC is a SORTED TABLE or INDEX TABLE. The BINARY SEARCH
    addition is only allowed for these tables if the key specified is an
    initial part of the table key."
    Please find detail
    TYES: tt_marc  TYPE SORTED TABLE OF marc   WITH NON-UNIQUE KEY matnr,werks.
    DATA: li_marc type tt_marc.
    READ TABLE li_marc INTO marc WITH KEY matnr = i_mbew-matnr     
                                                                          werks = i_mbew-bwkey BINARY SEARCH . 
    To my understanding , there is no need to mention Bianry Search  for sorted table TYPE. Please  let me know can  i use ?

    Hello,
    there is no need to mention Bianry Search for sorted table TYPE.
    Yes, this is because for SORTED TABLEs binary search algorithm is used by default for READ TABLE. Although you can use BINARY SEARCH addition but it's use is redundant.
    As for your case you've defined the KEY fields incorrectly There shouldn't be any "comma(s)" between the fields.
    TYPES: tt_marc TYPE SORTED TABLE OF marc WITH NON-UNIQUE KEY matnr werks.
    When you define it with commas
    TYPES: tt_marc TYPE SORTED TABLE OF marc WITH NON-UNIQUE KEY matnr, werks.
    the result is something like this:
    TYPES: tt_marc TYPE SORTED TABLE OF marc WITH NON-UNIQUE KEY matnr.
    TYPES: werks.
    Hence you were getting the syntax error!
    BR,
    Suhas
    PS: As for MARC you can use UNIQUE KEY addition because MATNR & WERKS are the key fields in the table.

Maybe you are looking for