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.

Similar Messages

  • 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

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

  • 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

  • Standard tables hashed tables

    in SORT we will not use sorted tables like where we will not use STANDARD TABLES and HASDED TABLES ........CAN U EXPLAIN IN DETAIL .......

    <b>Standard Internal Tables</b>
    Standard tables have a linear index. You can access them using either the index or the key. If you use the key, the response time is in linear relationship to the number of table entries. The key of a standard table is always non-unique, and you may not include any specification for the uniqueness in the table definition.
    This table type is particularly appropriate if you want to address individual table entries using the index. This is the quickest way to access table entries. To fill a standard table, append lines using the (APPEND) statement. You should read, modify and delete lines by referring to the index (INDEX option with the relevant ABAP command).  The response time for accessing a standard table is in linear relation to the number of table entries. If you need to use key access, standard tables are appropriate if you can fill and process the table in separate steps. For example, you can fill a standard table by appending records and then sort it. If you then use key access with the binary search option (BINARY), the response time is in logarithmic relation to
    the number of table entries.
    <b>Sorted Internal Tables</b>
    Sorted tables are always saved correctly sorted by key. They also have a linear key, and, like standard tables, you can access them using either the table index or the key. When you use the key, the response time is in logarithmic relationship to the number of table entries, since the system uses a binary search. The key of a sorted table can be either unique, or non-unique, and you must specify either UNIQUE or NON-UNIQUE in the table definition.  Standard tables and sorted tables both belong to the generic group index tables.
    This table type is particularly suitable if you want the table to be sorted while you are still adding entries to it. You fill the table using the (INSERT) statement, according to the sort sequence defined in the table key. Table entries that do not fit are recognised before they are inserted. The response time for access using the key is in logarithmic relation to the number of
    table entries, since the system automatically uses a binary search. Sorted tables are appropriate for partially sequential processing in a LOOP, as long as the WHERE condition contains the beginning of the table key.
    <b>Hashed Internal Tables</b>
    Hashes tables have no internal linear index. You can only access hashed tables by specifying the key. The response time is constant, regardless of the number of table entries, since the search uses a hash algorithm. The key of a hashed table must be unique, and you must specify UNIQUE in the table definition.
    This table type is particularly suitable if you want mainly to use key access for table entries. You cannot access hashed tables using the index. When you use key access, the response time remains constant, regardless of the number of table entries. As with database tables, the key of a hashed table is always unique. Hashed tables are therefore a useful way of constructing and
    using internal tables that are similar to database tables.
    <b>Index Tables</b>
    Index table is only used to specify the type of generic parameters in a FORM or FUNCTION. That means that you can't create a table of type INDEX.
    Internal tables are not DB tables. Standard and Sorted tables in combined are basically called as Index tables and there nothing else. Here is the hierarchy
              ANY TABLE
                                                |
                         |                                                    |
                 Index Tables                                    Hashed Table
                         |          
        |                                                     |
    Standard Table                      Sorted Table
    Reward  points if  it is usefull .....
    Girish

  • 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

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

  • How to search records in a standard table with * ?

    Hi everyone,
    Can anyone tell me how to search records in a standard table with * ?
    That is, in screen if user type * abc * for searching the records in which the field MC_STEXT contains 'abc'. What the code should be? How to complete the code below?
      SELECT SINGLE objid FROM p1000  INTO p1000-objid,
      WHERE MC_STEXT = ? .
    Thanks!

    Hi
    There are several way to do that, probably just as some guys wrote the easier way is to use LIKE in WHERE condition and the sign % instead of *:
    V_STRING = '%ABC%'.
    SELECT SINGLE objid FROM p1000 INTO p1000-objid,
    WHERE MC_STEXT LIKE V_STRING.
    U can also use a range (just like select-options):
    RANGES: R_MC FOR P1000-MC_STEXT.
    R_MC-LOW = 'ABC'.
    R_MC(3) = 'ICP'.
    APPEND R_MC.
    SELECT SINGLE objid FROM p1000 INTO p1000-objid,
    WHERE MC_STEXT IN R_MC.
    Max

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

  • Search Help for field of standard table used on non standar report

    Hi all.
    I need to know whether is posible to set up a "Search Help" / "Matchcode" for one standard field (LFBK-BKTVP) of a standard table (LFBK) that is going to be used on the selection screen of one new non standard report ZFK01.
    I was wondering if this could be posible under any special attributes, set up, ... for this field in the corresponding screen, but do not really know nor if that would work neither what to set up. Any other workaround would also be welcome.
    Could somebodly help?
    Thanks in advance. Regards,
    Abdali

    Hi ,
    Please try this code .It is working as per your requirement.
    *& Report  ZTESTPRO4                                      *
    REPORT  ztestpro4.
    TYPES:BEGIN OF ty_lfbk,
          bvtyp TYPE lfbk-bvtyp,
          END OF ty_lfbk.
    DATA:gt_lfbk TYPE STANDARD TABLE OF ty_lfbk,
         gs_lfbk TYPE ty_lfbk.
    PARAMETERS:bank TYPE lfbk-bvtyp.
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR bank.
      SELECT bvtyp
         FROM lfbk
         INTO TABLE gt_lfbk.
      CALL FUNCTION 'F4IF_INT_TABLE_VALUE_REQUEST'
        EXPORTING
          retfield    = 'BVTYP'
          dynpprog    = sy-repid
          dynpnr      = sy-dynnr
          dynprofield = 'bank'
          value_org   = 'S'
        TABLES
          value_tab   = gt_lfbk.

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

  • Replacemnt for read table with key binary search

    as read table with
    READ TABLE gt_INT_CURR_VALUE into gs_int_curr_value
               WITH KEY gs_FS_EINA_KEY  BINARY SEARCH.
    the statement read tabel with key is absolute in ecc 6 so how to replace it .

    Hi subratt,
    internal tables with header lines are obsolete and in oo context (CLASS / METHOD code) forbidden.
    OK, you'd better use SORTED TABLE and FIELD-SYMBOLS to gt optimal code::
    READ TABLE gt_INT_CURR_VALUE into gs_int_curr_value
    WITH KEY gs_FS_EINA_KEY BINARY SEARCH.
    may be replaced with
    DATA:
      gt_INT_CURR_VALUE_SORTED LIKE SORTED TABLE OF  gs_int_curr_value
        WITH [NON-]UNIQUE KEY <fields of  gs_FS_EINA_KEY>.
    FIELD-SYMBOLS:
      <nt_curr_value> LIKE gs_int_curr_value.
    gt_INT_CURR_VALUE_SORTED = gt_INT_CURR_VALUE.
      READ TABLE gt_INT_CURR_VALUE_SORTED ASSIGNING <nt_curr_value>
        WITH TABLE KEY <key1> = gs_FS_EINA_KEY-<key1> ..  <keyn> = gs_FS_EINA_KEY-<keyn>.
    Regards,
    Clemens

  • Attach search help to standard table field

    Hi,
    I need to attach search help to standard table field VBKD-EMPST.
    I have create a z search help and taken acess key from SAP.
    But unable to attach this to standard table field.
    Kindly help.
    Moderator message: duplicate post locked.
    Edited by: Thomas Zloch on Oct 27, 2010 6:11 PM

    Hi,
    just go throw this link
    Re: Attaching Search Help to a field
    I hope this will help u
    Thanks
    Regards
    Akhilesh Singh

  • Hash lookup or Binary search to fetch data from internal table

    Hi All,
    I want to know Which is faster, Hash lookup or Binary search to fetch data from internal tables?
    Thanks,
    Mahesh
    Moderator Message: Duplicate post
    Edited by: kishan P on Oct 14, 2010 4:22 PM

    type mod* .the the sign would change to pattern.try and see.i checked.reward if works.

  • How to change the search help in the standard table?

    Hello Experts,
    Due to service package installation the search help in standard table (VBAP)  field (KDMAT) was changed from Collective search help (VMCV)  to elementary search help (VMCVA).
    Now I need to change the elementary search help to Collective search help, without taking the Access Key.
    Please suggest me the appropriate solution

    hi
    In SE11, go to the change mode of the collective search help and add the elementary search help, in the INCLUDED SEARCH HELPS tab.for including elementary search help, you just have to enter the name of search help along with its parameter in collective search help
    system autimatically takes selection method and dialog from elementary search help
    regards
    Prashant

Maybe you are looking for

  • Licensing Issue Quality Management 9.0 with UCCX 8.5

    Hi guys, The UCCX compatibility matrix, Cisco WFO System config Guide plus QM 9.0 installation guide all state QM9.0 is compatible with UCCX 8.5(SU3). We have ordered QM9.0 licenses using part number L-CCX-90-QM-L-K9=:L-CCX-90-QM-L-K9= : CCX 9.0 Qual

  • Is it possible to embed publisher metadata in a pdf so it shows in ADE

    Currently all I get is 'Publisher unknown'. Have seen various threads about this from a couple of years ago when it seems it wasn't possible, has this changed?

  • Session variable not passing between pages

    Hi, I've got a form that calculates checkbox values and puts them in a total field called txtTotal. When the user clicks send, I need to pass the total to a payment page.  The form page has PHP session_start(); $_SESSION['sessTotal'] = $_POST['txtTot

  • Cannot log in and connect to Skype

    I've been using Skype for a while, until recently when I entered my Skype Name and Password, it'll just stay on the "signing in" page with the circle spinning. Then after a while, it'll take me back to the "welcome to Skype" sigh in page with a box s

  • Displaying qoutation in pdf format

    Hi Friends,      I have developed Quotation(script) .  My main requirement is to display the output in PDF format, for that i changed the driver program as instructed by many friends, but i am getting error as "OTF end command // missing in OTF data"