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

Similar Messages

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

  • A little urgent when to use binary search.

    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> <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.
    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 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
    reward if useful.
    Thanks,
    Madhukar

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

  • 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

  • Please explain how to use binary search in this loop.

    Hi,
    I want to use the binary search in below Read please give me solution....
    LOOP AT it_vbfa_temp ASSIGNING <fs_vbfa_temp>.
          CLEAR is_ekbz1.
          READ TABLE it_ekbz1 INTO is_ekbz1 WITH KEY xblnr = <fs_vbfa_temp>-deliv flag = space.
          IF  sy-subrc = 0.
            w_tabix = sy-tabix.
            is_ekbz1-tknum = <fs_vbfa_temp>-shipno.
            is_ekbz1-flag  = 'X'.
            MODIFY it_ekbz1 FROM is_ekbz1 INDEX w_tabix TRANSPORTING tknum flag.
    ENDLOOP.

    Hi,
    Thanks for the inputs given.. Please find the solution for the same ....
       CLEAR is_ekbz1.
        is_ekbz1-flag = 'X'.
        MODIFY it_ekbz1 FROM is_ekbz1 TRANSPORTING flag WHERE flag IS INITIAL.
        SORT it_ekbz1 BY ebeln xblnr lifnr flag.
      LOOP AT it_vbfa_temp ASSIGNING <fs_vbfa_temp>.
          CLEAR is_ekbz1.
          READ TABLE it_ekbz1 INTO is_ekbz1 WITH KEY xblnr = <fs_vbfa_temp>-deliv flag = 'X' BINARY SEARCH.
          IF  sy-subrc = 0.
            w_tabix = sy-tabix.
            is_ekbz1-tknum = <fs_vbfa_temp>-shipno.
            is_ekbz1-flag  = space.
            MODIFY it_ekbz1 FROM is_ekbz1 INDEX w_tabix TRANSPORTING tknum flag.
      ENDLOOP.
    Regards,
    Srinivas
    Edited by: Srininas on Apr 6, 2010 12:16 PM
    Edited by: Srininas on Apr 6, 2010 12:17 PM

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

  • 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

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

  • 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

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

    Hi,
    I keep getting a java.lang.ClassCastException with these two classes when I try to perform a binary search. Any tips?
    Phonebook class:
    =============
    import java.util.*;
    public class Phonebook
    private static long comparisons = 0;
    private static long exchanges = 0;
         public static void main (String[] args)
         // Create an array of Phonebook records
         PhoneRecord[] records = new PhoneRecord[10];
         records[0] = new PhoneRecord("Smith","Bob", 1234367);
         records[1] = new PhoneRecord("Jones","Will", 1234548);
         records[2] = new PhoneRecord("Johnson","Frank", 1234569);
         records[3] = new PhoneRecord("Mc John","Pete", 1234560);
         records[4] = new PhoneRecord("OBrien","Frank", 1234571);
         records[5] = new PhoneRecord("OConnor","Joe", 1234572);
         records[6] = new PhoneRecord("Bloggs","Ricky", 1233570);
         records[7] = new PhoneRecord("empty","empty", 8888888);
         records[8] = new PhoneRecord("empty","empty", 9999999);
         records[9] = new PhoneRecord("Van Vliet","Margreet", 1244570);
         // call menu
         Menu(records);
         } // end main
    //================================================
    // menu
    //================================================
    static void Menu(PhoneRecord[] records)
         int option;
         // menu options
         System.out.println("===========Menu==============================");
         System.out.println("=============================================");
         System.out.println(" ");
         System.out.println("1. Find record (Advanced Search) ");
         System.out.println("2. Quick Search ");
         System.out.println("3. Add a record ");
         System.out.println("4. Show database ");
         System.out.println("5. Sort database ");
         System.out.println("6. Exit     ");
         System.out.println(" ");
         System.out.println("=============================================");
         System.out.println("=============================================");
         System.out.println(" ");
         System.out.println("Choose a number ");
         option = Console.readInt();
         // every menu option has its own method
         if (option == 1)
              FindRecord(records);
         if (option == 2)
              QuickSearch(records);
         else if (option == 3)
              AddRecord(records);
         else if (option == 4)
              ShowDatabase(records);
         else if (option == 5)
              quickSort(records, 0, 9);
              ShowDatabase(records);
         // if 6 then terminate the program
         else
                   System.out.println("Goodbye!");
    } // end of menu
    //=================================================
    // menu option 1: Find a record - using linear search
    //=================================================
    static void FindRecord(PhoneRecord[] records)
    int option;
    do
    // the user can search based on first name or last name
    System.out.println("Do you want to search for:");
    System.out.println("1. First Name");
    System.out.println("2. Last Name");
    System.out.println("3. End search");
    option = Console.readInt();
         // option 1 is search based on first name
         if (option == 1)
              System.out.println("Enter First Name");
              String first = Console.readString();
              int notthere = -1;
              for (int i=0; i < 10; i++)
                   if (first.equals(records.first_Name))
                        System.out.println("----------------------------------");
                        System.out.println(records[i].last_Name + ", " + records[i].first_Name);
                        System.out.println(records[i].phonenumber);
                        System.out.println("----------------------------------\n\n");
                   // if a record is found, the variable notthere will be > -1
                   notthere = i;
              } // end search array
                   // if notthere is -1, then there is no record available
                   if (notthere < 0)
                   System.out.println("------------------------------");
                   System.out.println("No record available");
                   System.out.println("------------------------------\n\n");
         } // end option 1 First Name
         // option 2 allows the user to search based on last name
         else if (option == 2)
              System.out.println("Enter Last Name");
              String last = Console.readString();
              int notthere = -1;
              for (int i=0; i < 10; i++)
                   if (last.equals(records[i].last_Name))
                        System.out.println("----------------------------------");
                        System.out.println(records[i].last_Name + ", " + records[i].first_Name);
                        System.out.println(records[i].phonenumber);
                        System.out.println("----------------------------------\n\n");
                   notthere = i;
                   // if notthere is -1 then there is no record available
                   // if notthere is > -1 then there is a record available
                   } // end search array
                   if (notthere < 0)
                   System.out.println("------------------------------");
                   System.out.println("No record available");
                   System.out.println("------------------------------\n\n");
         } // end option 2 Last Name
         else
              // if the user types in a wrong number, he or she returns to the menu
              Menu(records);
    while (option != 3);
    } // end FindRecord
    //=================================================
    // menu option 2: Quick Search - using binary search
    //=================================================
    static void QuickSearch(PhoneRecord[] records)
         // Sort array - Using Quicksort
         quickSort(records, 0, 9);
         // allow user to enter the last name
         System.out.println("Enter Last Name");
         String last = Console.readString();
         // use binary search to find the target
         int index = binarySearch(records, last);
         // -1 means that there are no records
         if (index == -1)
         System.out.println("------------------------------");
         System.out.println("No record available");
         System.out.println("------------------------------\n\n");
         // print out the record
         System.out.println("----------------------------------");
         System.out.println(records[index].last_Name + ", " + records[index].first_Name);
         System.out.println(records[index].phonenumber);
         System.out.println("----------------------------------\n\n");
         // return to menu
         Menu(records);
    } // end QuickSearch
    public static int binarySearch( Comparable [ ] a, Comparable x )
    int low = 0;
    int high = 9;
    int mid;
    while( low <= high )
    mid = ( low + high ) / 2;
    if( a[ mid ].compareTo( x ) < 0 )
    low = mid + 1;
    else if( a[ mid ].compareTo( x ) > 0 )
    high = mid - 1;
    else
    return mid;
    return -1; // not found
    //=================================================
    // menu option 3: Add a record
    //=================================================
    static void AddRecord(PhoneRecord[] records)
    int option;
    int index = 0;
    // enter details
    do
         // to say that the array is not full yet, I use the variable filled
         int filled = 0;
    System.out.println("Enter the First Name");
    String frst = Console.readString();
    System.out.println("Enter the Last Name");
    String lst = Console.readString();
    System.out.println("Enter the phone number");
    int phn = Console.readInt();
    // search the array for the empty slot
         for (int i=0; i < 10; i++)
              if (records[i].first_Name.equals("empty") && filled == 0)
              records[i].first_Name = frst;
              records[i].last_Name = lst;
              records[i].phonenumber = phn;
              filled = 1;
         // Sort array - Using Quicksort
         quickSort(records, 0, 9);
         // Print out sorted values
         for(int i = 0; i < records.length; i++)
              System.out.println("----------------------------------");
              System.out.println(records[i].last_Name + ", " + records[i].first_Name);
              System.out.println(records[i].phonenumber);
              System.out.println("----------------------------------\n\n");
         System.out.println("Do you want to add more records?");
         System.out.println("1. Yes");
         System.out.println("2. No");
         option = Console.readInt();
         if (option == 2)
              Menu(records);
         // sets the database to full
         int empty = 0;
         for (int i=0; i < 10; i++)
              // empty = 1 means that there is an empty slot
              if (records[i].first_Name.equals("empty"))
                   empty = 1;
         // if the system didn't find an empty slot, the database must be full
         if (empty == 0)
         System.out.println("Database is full");
         option = 2;
         Menu(records);
    while (option != 2);
    } // end AddRecord
    //=================================================
    // menu option 4: Show database
    //=================================================
    static void ShowDatabase(PhoneRecord[] records)
              // shows the entire database
              for (int i=0; i < 10; i++)
                        System.out.println("----------------------------------");
                        System.out.println(records[i].last_Name + ", " + records[i].first_Name);
                        System.out.println(records[i].phonenumber);
                        System.out.println("----------------------------------");
         Menu(records);
    //===============================================
    // Sort array
    //=============================================
    public static void quickSort (Comparable[] a, int left, int right)
         // Sort a[left?right] into ascending order.
         if (left < right) {
         int p = partition(a, left, right);
         quickSort(a, left, p-1);
         quickSort(a, p+1, right);
    static int partition (Comparable[] a, int left, int right)
         // Partition a[left?right] such that
         // a[left?p-1] are all less than or equal to a[p], and
         // a[p+1?right] are all greater than or equal to a[p].
         // Return p.
         Comparable pivot = a[left];
         int p = left;
         for (int r = left+1; r <= right; r++) {
         int comp = a[r].compareTo(pivot);
         if (comp < 0) {
         a[p] = a[r]; a[r] = a[p+1];
    a[p+1] = pivot; p++;          }
         return p;
    } // end class PhoneBook
    PhoneRecord class:
    ================
    public class PhoneRecord implements Comparable
    public int phonenumber;
    public String last_Name;
    public String first_Name;
    public PhoneRecord(String last_Name, String first_Name, int phonenumber)
    this.last_Name = last_Name;
    this.phonenumber = phonenumber;
    this.first_Name = first_Name;
    /* Overload compareTo method */
    public int compareTo(Object obj)
    PhoneRecord tmp = (PhoneRecord)obj;
    // sorting based on last name
    String string1 = this.last_Name;
    String string2 = tmp.last_Name;
    int result = string1.compareTo(string2);
    if(result < 0)
    /* instance lt received */
    return -1;
    else if(result > 0)
    /* instance gt received */
    return 1;
    /* instance == received */
    return 0;

    JosAH wrote:
    prometheuzz wrote:
    bats wrote:
    Hi,
    I keep getting a java.lang.ClassCastException with these two classes when I try to perform a binary search. Any tips?
    ...Looking at your binary search method:
    public static int binarySearch( Comparable [ ] a, Comparable x)I see it expects to be fed Comparable objects. So, whatever you're feeding it, it's not a Comparable (ie: it doesn't implement Comparable), hence the CCE.It's even worse: if an A is a B it doesn't make an A[] a B[].
    kind regards,
    JosMy post didn't make much sense: if there were no Comparables provided as an argument, it would have thrown a compile time error. The problem lies in the compareTo(...) method.

Maybe you are looking for