Start of Content Area

Binary Search in Standard Tables  Locate the document in its SAP Library structure

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

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

REPORT demo_int_tables_read_index_bin.

DATA: BEGIN OF line,
        col1 TYPE i,
        col2 TYPE i,
      END OF line.

DATA itab LIKE STANDARD TABLE OF line.

DO 4 TIMES.
  line-col1 = sy-index.
  line-col2 = sy-index ** 2.
  APPEND line TO itab.

ENDDO.

SORT itab BY col2.

READ TABLE itab WITH KEY col2 = 16 INTO line BINARY SEARCH.

WRITE: 'SY-SUBRC =', sy-subrc.

The list 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.

 

 

End of Content Area