"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

Similar Messages

  • 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

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

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

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

  • When to use binary search ... little urgent.

    Hi evryone,
    Plz let me know under what kind of conditions can we use binary search addition cause if I use it for every read statement the database acees in se30 goes higher than normal.
    If i randomly select only a few big read table statements the database acees in se30 goes is slightly lesser.
    But I some how dont know where to use binary search and where not to with read statements.
    Expecting an early reply.
    Rgds,
    Anu

    Hi,
    If  you read entries from standard tables using a key other than the default key, you can use a binary search instead of the normal linear search. To do this, include the addition BINARY SEARCH in the corresponding READ statements.
    READ TABLE <itab> WITH KEY <k1> = <f1>... <kn> = <fn> 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.
    BINARY SEARCH approaches the middle entry in the table, decides if it matches, or lexically greater than or equal to the key being searched. It accordingly skips either the top or bottom part of the internal table and searches the other half. It repeats this process till it finds the row.
    Using BINARY SEARCH with READ is the most efficient way to read standard internal tables which are sorted by the key used to search them
    BINARY SEARCH addition when reading a sorted table is not required, as it happens by default. It makes a good difference in performance if you are reading a large standard internal table without sorting and reading by BINARY SEARCH.
    Regards,
    Padmam.

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

  • Binary Search in Dynamic Read

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

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

  • 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...BINARY SEARCH for more than 1 row.

    Hi,
    i have an internal table that contains several same entries. now i want to search the table with READ ... BINARY SEARCH ( or in another efficient way ) and get all those entries and not just one/the first one.
    how could i do that ? thanks in advance!

    hi leider,
    plz c the below sample code.
    loop at i_head into workarea.
    READ TABLE i_zvfx_gts008_itm INTO wa_zvfx_gts008_itm
                                     WITH KEY
                                     bukrs     = wa_zvfx_gts008_head-bukrs
                                  zzinvoice = wa_zvfx_gts008_head-zzinvoice
                                     BINARY SEARCH.
        IF sy-subrc EQ 0.
          LOOP AT i_zvfx_gts008_itm INTO wa_zvfx_gts008_itm FROM sy-tabix.
            IF ( wa_zvfx_gts008_itm-bukrs NE wa_zvfx_gts008_head-bukrs ) OR
          ( wa_zvfx_gts008_itm-zzinvoice NE wa_zvfx_gts008_head-zzinvoice ).
              EXIT.
            ENDIF.
    endloop.
    this is something like avoiding loop at where condition.
    plz reward points if found helpful.

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

  • Read table  binary search

    Hi all,
    Can i use raed table binary search for Hased tables? I coded like this
    DATA:T_MODEL_HASH LIKE HASHED TABLE OF T_MODEL
    WITH UNIQUE KEY PBPINO  WITH HEADER LINE.
    READ TABLE t_model_hash WITH KEY pbpino = t_zwpbph-pbpapino
        BINARY SEARCH.
    But iam getting syntax error "cannot use explicit or implicit index operations on hased tables ".can any one let me know about this issue?

    Hi Priya,
    Hashed tables are managed by a hash algorithm. There is no logical index. The entries are not ordered in the memory. The position of a row is calculated by specifying a key using a hash function.
    A hashed table's performance in reads is NOT dependent on the number of records. However, it is intended for reads that will return only and only one record. It uses a "side-table" with a hash algorithm to store off the physical location of the record in the actual internal table. It is not NECESSARILY sorted/organized in an meaningful order (like a sorted table is). Please note that changes to a hashed tables records must be managed carefully.
    Please check this link to understand how to use hash table.
    http://help.sap.com/saphelp_erp2004/helpdata/en/fc/eb362c358411d1829f0000e829fbfe/frameset.htm
    Regards,
    Ferry Lianto

  • 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

  • Read Itab binary search not working.

    Hi,
    I have the following issue:
    From a table, I am picking up 5 fields into an internal table (in the correct sequence):
    A B C D E.
    Now, I am sorting the above internal table as follows:
    sort itab by A B C descnding.
    Now, I am writing the read stmt as follows:
    read table itab into wa_itab with key
                                  A = var1
                                  B = var2
                                  C = car3
                                 Binary Search.
    But, the read fails in most of the cases even though the exact values exist in the itab. It does not fail always, but fails for majority of the cases, though the exact matches are present in the itab.
    If I remove the Binary Search option, it works fine.
    Could you please let me know if I am missing out on anything here?
    Please let me know if any more information is needed.
    Thank You,
    Anjana Banerjee

    Hi anjana,
    please do not ask questions before reading the online help:
    ["The standard table must be sorted in ascending order by the specified search key. "|http://help.sap.com/saphelp_nw73/helpdata/en/fc/eb373d358411d1829f0000e829fbfe/frameset.htm]
    Regards,
    Clemens

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

Maybe you are looking for

  • Image hyperlink issues in PDF creation using Acrobat 9.0

    Hi All, I am using Acrobat 9.0 Professional for creating a PDF of a web site hosted on my local IIS server. All the web pages contain:            1. A single large image and some description text.            2. Few hyperlinks mapped to the various ar

  • ITunes cannot open files in the "MP3 Audio File" format

    Lately I've been getting this error that iTunes can't open MP3 files. It happens when I try to double click on an MP3, however, if I click and drag the MP3 into my iTunes library it opens fine. Not a huge problem....just a nuisance. Running iTunes 10

  • Rename a file!

    can i rename more than one file at the same time.. coz this option is working in windows xp, for example u can select 10 files and then rename them with the name "VALDI" so it will automatically rename the rest of files valdi1, valdi2, valdi3, valdi4

  • Can I delete logic pro 9 and keep all the loops for logic pro X

    I am running out of space on my computer and I want to delete as much as I can. I need to know if i delete logic pro 9 will i lose all apple loops for logic pro X.

  • Exporting Pro CS4 videos to different mpeg formats-no video or separate audio file???

    I have Premiere Pro CS4. When I export my video to mpeg-4 format, there is no video. When I export to mpeg-2DVD format, there is a separate wav audio file. Adobe Media Encoder, which I use automatically as the export encoding software, does not seem