Linear Search

I got this Linear input example from many site and somehow its standard.
Question:
1)What to add to ActionListenerListener class so that it will go to search class,Search class is on a seperate file .Example of the ActionListener is below Search class.
2)How to modify the Search class or actionListener,so that when a serial no is keyed in, it will return the value to the textield in the GUI
Example:Assume there is 5 data IcNum,Brand ,model,Cost,SerialNo that is already stored inside as a single object.
Stupid GUI
Enter SerialNO: ****** 10AHT0UjaiUja6 (textfield)*
*Search button *
Model :****
Cost :                                                                        -      
(when search is pressed and matched Serial No, it will show entry that is already stored on the empty textfield even though there is 5 data in a single object and asked to return 2 of them)
public class Search
     public static int linearSearch(int[] a, int first, int upto, int key) {
    for (int i = first; i < upto; i++) {
        if (key == a) {
return i; // Found key, return index.
return -1; // Failed to find key
Example of my Listener
  b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
        });RockmanEXE

1) Next time be more specific about exactly what problem you're having. Paste in the error and indicate exactly which line it's occurring on or describe the observed vs. expected behavior in detail.
2) = is for assignment, == is for comparison.
3) You don't need compareTo() here. equals() will do fine.

Similar Messages

  • Linear search between two arrays

    I'm having trouble with the comparison of an array of football teams and an array of team names that may or may not be in the football team array. I have read both .txt files into their own arrays and parsed the team array with substring in order to isolate the team name. I know I can read both the search array and the team names individually because I tested it with a println. I think my problem is in the comparison "if" statement.
        public void seqSearch()//Sequential(linear) search
        int j=0, s;
        //int m = j+1;
            for(s=0; s<searchSize; s++)//increments through the search array
              for(j=0; j<teamArray.length; j++)//increments through the team array
               if(teamArray[j].getName().equals(search[s]))//I think this is where the problem is
                   System.out.println("Found " + teamArray[j].getName() + "after" + j + "searches.");
                   break;                 
               else
                   System.out.println(teamArray[j].getName());//prints through all of the names during each search for testing
                   if(j == teamArray.length-1)
                       System.out.println("Can't find " + search[s] + " after " + j + " searches");
            }//end for
        }//end seqSearch()My output prints the names of each team on their own line and at the end it always says that it can't find each search term.
    Ex.
    Bears
    Bengals
    Bills
    Vikings
    Can't find Bills after 32 searches
    Bears
    Bengals
    Bills
    Vikings
    Can't find Eagles after 32 searches
    etc
    I though that .equals was the way to compare in this situation. Any idea what I'm doing wrong?

    Dave,
    teamArray[j].getName().equals(search[s]))what is the implementation class which is returned from "search[s]" and from "eamArray[j].getName()"
    if both of them are java.lang.String then us "equalsIgnoreCase" instead of "equals"
    if the implementation class is different, then you have to override the equal method and implement your own.
    Regards,
    Alan Mehio
    London, UK

  • Linear search and binary search

    Hi
    can any one tell me what is linear and binary search in detail.
    and what is the difference between them .
    which one is useful in coding.
    Thanks&Regards,
    S.GangiReddy.

    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 value 16.
    Linear search use sequential search means each and every reord will be searched to find. so it is slow.
    Binary search uses logrim for searching. Itab MUST be sorted on KEY fields fro binary search. so it is very fast.
    The search takes place as follows for the individual table types :
    standard tables are subject to a linear search. If the addition BINARY SEARCH is specified, the search is binary instead of linear. This considerably reduces the runtime of the search for larger tables (from approximately 100 entries upwards). For the binary search, the table must be sorted by the specified search key in ascending order. Otherwise the search will not find the correct row.
    sorted tables are subject to a binary search if the specified search key is or includes a starting field of the table key. Otherwise it is linear. The addition BINARY SEARCH can be specified for sorted tables, but has no effect.
    For hashed tables, the hash algorithm is used if the specified search key includes the table key. Otherwise the search is linear. The addition BINARY SEARCH is not permitted for hashed tables.
    Binary search must be preffered over linear sarch.
    Hope this is helpful, Do reward.

  • Difference between Binary search and Linear search

    Dear all,
    If anyone helps me to get the basic difference between binary and Linear search in SAP environment.
    Regards

    Hi,
    In case of linear search system will search from begining.
    that means Example : z table contains single field with values 
    1 2 3 4 5 6 7 8 9 
    if u r searching for a value then system will starts from
    first position. if required value is founded then execution
    will comes out from z table.
    In case of binary search system will starts from mid point.
    if value is not founded then it will search for upper half.
    in  that upper half it will check mid point.like that search
    will takes place.
    Thanks,
    Sridhar

  • Linear and Binary Searching of Parallel Arrays

    I'm an AP student who used the "Fundamentals of Java" by Lambert/Osborne 3rd Edition. This text book has code that doesn't match anything else I've found in other how-to's, guides, or teach yourself books. Not even online can I find code that matches up with the format used in this book!
    I've got an assignment that wants me to read in a 4 digit account number of N number of customers, places them in two parallel arrays. Data found in two separate txt files. Create a prompt that ask's for customer's account number then displays account balance. Same program for both linear and binary search methods (2 programs).
    I know the search method and how to read the files with a scanner. It is the body of the program that is stumping me. How to call and search the arrays themselves. Any help would be great.

    First of all, you have posted this question in the wrong place. Please post these kinds of general questions in the New to Java forum.
    Second, if you're in an AP class, don't you have a teacher you can ask?
    But anyway, here's the idea
    For a linear search, you go thru the array element by element, and on each element you call equals(x) to see if that element is equal to what you're searching for (note that primitives use == rather than equals)
    For binary search, note first of all that your data MUST BE COMPARABLE (primative or implement the comparable interface) and MUST BE SORTED.
    Then what you can do if go to the middle of the list, and if what you are searching for is less than that element, go to the middle of the first half of the list (if it's greater, go the the middle of the upper half of the list) and keep breaking the list in half until you've found the element or you know its not there.

  • Difference between Linear & Binary search.

    Hi,
           Could Anybody describe me, What is the difference between Linear Search and Binary Search in ABAP ?
    Moderator Message: Please search before posting your question. Therad locked.
    Edited by: Suhas Saha on Oct 19, 2011 11:21 AM

    Hi,
    In case of linear search system will search from begining.
    that means Example : z table contains single field with values 
    1 2 3 4 5 6 7 8 9 
    if u r searching for a value then system will starts from
    first position. if required value is founded then execution
    will comes out from z table.
    In case of binary search system will starts from mid point.
    if value is not founded then it will search for upper half.
    in  that upper half it will check mid point.like that search
    will takes place.
    Thanks,
    Sridhar

  • Sorting and Searching String (Please help me)

    Hi, Could somn please be of any help here. I am trying to sort this string in alphabetical order and then search for data available but I am not makingprogress with the code. Does anyone have any advise or better still the code to solve this problem... This is hat I have at the moment
    import java.util.*;
    import java.io.PrintStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    public class coursework2
         public static final int MAX_RECORDS = 20;
         public static String lastName[] = new String[MAX_RECORDS];
         public static String firstName[] = new String[MAX_RECORDS];
         public static String telNumber[] = new String[MAX_RECORDS];
         public static String emailAddress[] = new String[MAX_RECORDS];
         public static int read_in_file(String file_name)
              Scanner read_in;
              Scanner line;
              int record_count = 0;
              String record;
              try
                   read_in = new Scanner(new File(file_name));
                   // read in one line at a time
                   read_in.useDelimiter(System.getProperty("line.separator"));
                   while (read_in.hasNext())
                        // Test to see if there are too many records in the file
                        if (record_count == MAX_RECORDS)
                             System.out.printf("Only %d records allowed in file", MAX_RECORDS);
                             System.exit(0);
                        // read in record
                        record = new String(read_in.next());
                        // Split the record up into its fields and store in
                        // appropriate arrays
                        line = new Scanner(record);
                        line.useDelimiter("\\s*,,\\s*");
                        lastName[record_count] = line.next();
                        firstName[record_count] = line.next();
                        telNumber[record_count] = line.next();
                        emailAddress[record_count] = line.next();
                        // Increment record count
                        record_count++;
              catch (FileNotFoundException e)
                   e.printStackTrace();
              return record_count;
         public static void write_out_file(int no_of_records, String filename)
              PrintStream write_out;
              int counter;
              try
                   // Create new file
                   write_out = new PrintStream(new File(filename));
                   // Output all reacords
                   for(counter = 0; counter < no_of_records; counter++)
                        // Output a record
                        write_out.print(lastName[counter]);
                        write_out.print(",,");
                        write_out.print(firstName[counter]);
                        write_out.print(",,");
                        write_out.print(telNumber[counter]);
                        write_out.print(",,");
                        write_out.println(emailAddress[counter]);
                   // Close file
                   write_out.close();
              catch (FileNotFoundException e)
                   e.printStackTrace();
         // Your 'functions' go here
         //This code sorts out the record after loaded into alphabetical order using
         //the selection sort method
         public static void sort()
         // Your 'main' code goes here
         //The code below uses a binary search method to search for record because
         //record have been sorted and this would make search faster and more efficient
         public static boolean linearSearch(String strFirstName, String strLastName)
              //Set-up data_input and declare variables
              //This linear search searches for record in the contact application.
              //Search for a record using surname only
                   int i = 0;
                   boolean found = false;
                   while (!found && i < lastName.length)
                        if(strFirstName.equals("") && strLastName.equals(""))
                             return true;
                        if(lastName.equalsIgnoreCase(strLastName)){
                   //List records from surname only
                   System.out.println("Enter your search criteria (last name only):");
                        System.out.print(lastName[i] +     "\t" + firstName[i] + "\t" + telNumber[i] +"\t" + emailAddress[i]);
                        System.out.println("");
                        if (lastName[i].compareTo(strLastName) == 0)
                             //Compare the last name values and type to make sure they are same.
                             found = true;
                                  i++;
                                  System.out.print(lastName[i] +     "\t" + firstName[i] + "\t" + telNumber[i] +"\t" + emailAddress[i]);
                                       System.out.println("");
                             return found;
              //Search for a record using first name only
         public static void main(String[] args)
              // Set-up data input
              Scanner data_input = new Scanner(System.in);
              // Declare Variables
              int number_of_records;
              String filename;
              int counter;
              // Get filename and read in file
              System.out.print("Enter the masterfile file name: ");
              filename = data_input.next();
              number_of_records = read_in_file("data2.dat");
              //Get new filename and write out the file
              System.out.print("Enter new masterfile file name: ");
              filename = data_input.next();
              //System.out.println("Enter your search criteria (first or last name):");
              linearSearch("*", "");
    Am very sorry this is long, the file should be sorted after it is loaded and I have that, You can make up some data with last ane, first name, tel and email to show me an example. Thanks alot
    Joseph

    Hi Monica, Thanks for you patience with me.
    I have tried writing a selection sort method but am having some errors. Could you kindly have a lookand correct me please.
    This is the code i wrote
    public static void selectionSort(Comparable [] data)
              String strFirstName;
              String strLastName;
              Comparable temp;
              for(int i = 0; i < lastName.length; i++)
                   lastName = index;
                   for (int j = i; j < lastName.length; j++)
                        if (lastName[j].compareTo(lastName) < 0)
                             lastName[j] = lastName[i];
                   //Swap the string values
                   temp = lastName[j];
                   lastName[j] = lastName[i];
                   lastName[i] = temp;
    As you requested, below are 4 error messages I had
    E:\coursework2.java:101: cannot find symbol
    symbol : variable index
    location: class coursework2
                   lastName = index;
    ^
    E:\coursework2.java:107: cannot find symbol
    symbol : variable j
    location: class coursework2
                   temp = lastName[j];
    ^
    E:\coursework2.java:108: cannot find symbol
    symbol : variable j
    location: class coursework2
                   lastName[j] = lastName[i];
    ^
    E:\coursework2.java:109: incompatible types
    found : java.lang.Comparable
    required: java.lang.String
                   lastName[i] = temp;
    ^
    4 errors
    JCompiler done.
    JCompiler ready.
    Joseph

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

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

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

  • Handle long-running EDT tasks (f.i. TreeModel searching)

    Note: this is a cross-post from SO
    http://stackoverflow.com/questions/9378232/handle-long-running-edt-tasks-f-i-treemodel-searching
    copied below, input highly appreciated :-)
    Cheers
    Jeanette
    Trigger is a recently re-detected SwingX issue (https://java.net/jira/browse/SWINGX-1233): support deep - that is under collapsed nodes as opposed to visible nodes only, which is the current behaviour - node searching.
    "Nichts leichter als das" with all my current exposure to SwingWorker: walk the TreeModel in the background thread and update the ui in process, like shown in a crude snippet below. Fest's EDT checker is happy enough, but then it only checks on repaint (which is nicely happening on the EDT here)
    Only ... strictly speaking, that background thread must be the EDT as it is accessing (by reading) the model. So, the questions are:
    - how to implement the search thread-correctly?
    - or can we live with that risk (heavily documented, of course)
    One possibility for a special case solution would be to have a second (cloned or otherwise "same"-made) model for searching and then find the corresponding matches in the "real" model. That doesn't play overly nicely with a general searching support, as that can't know anything about any particular model, that is can't create a clone even if it wanted. Plus it would have to apply all the view sorting/filtering (in future) ...
    // a crude worker (match hard-coded and directly coupled to the ui)
    public static class SearchWorker extends SwingWorker<Void, File> {
        private Enumeration enumer;
        private JXList list;
        private JXTree tree;
        public SearchWorker(Enumeration enumer, JXList list, JXTree tree) {
            this.enumer = enumer;
            this.list = list;
            this.tree = tree;
        @Override
        protected Void doInBackground() throws Exception {
            int count = 0;
            while (enumer.hasMoreElements()) {
                count++;
                File file = (File) enumer.nextElement();
                if (match(file)) {
                    publish(file);
                if (count > 100){
                    count = 0;
                    Thread.sleep(50);
            return null;
        @Override
        protected void process(List<File> chunks) {
            for (File file : chunks) {
                ((DefaultListModel) list.getModel()).addElement(file);
                TreePath path = createPathToRoot(file);
                tree.addSelectionPath(path);
                tree.scrollPathToVisible(path);
        private TreePath createPathToRoot(File file) {
            boolean result = false;
            List<File> path = new LinkedList<File>();
            while(!result && file != null) {
                result = file.equals(tree.getModel().getRoot());
                path.add(0, file);
                file = file.getParentFile();
            return new TreePath(path.toArray());
        private boolean match(File file) {
            return file.getName().startsWith("c");
    // its usage in terms of SwingX test support
    public void interactiveDeepSearch() {
        final FileSystemModel files = new FileSystemModel(new File("."));
        final JXTree tree = new JXTree(files);
        tree.setCellRenderer(new DefaultTreeRenderer(IconValues.FILE_ICON, StringValues.FILE_NAME));
        final JXList list = new JXList(new DefaultListModel());
        list.setCellRenderer(new DefaultListRenderer(StringValues.FILE_NAME));
        list.setVisibleRowCount(20);
        JXFrame frame = wrapWithScrollingInFrame(tree, "search files");
        frame.add(new JScrollPane(list), BorderLayout.SOUTH);
        Action traverse = new AbstractAction("worker") {
            @Override
            public void actionPerformed(ActionEvent e) {
                setEnabled(false);
                Enumeration fileEnum = new PreorderModelEnumeration(files);
                SwingWorker worker = new SearchWorker(fileEnum, list, tree);
                PropertyChangeListener l = new PropertyChangeListener() {
                    @Override
                    public void propertyChange(PropertyChangeEvent evt) {
                        if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
                            //T.imeOut("search end ");
                            setEnabled(true);
                            ((SwingWorker) evt.getSource()).removePropertyChangeListener(this);
                worker.addPropertyChangeListener(l);
                // T.imeOn("starting search ... ");
                worker.execute();
        addAction(frame, traverse);
        show(frame)
    }

    At the end of the day, it turned out that I asked the wrong question (or right question in a wrong context ;-): the "problem" arose by an assumed solution, the real task to solve is to support a hierarchical search algorithm (right now the AbstractSearchable is heavily skewed on linear search).
    Once that will solved, the next question might be how much a framework can do to support concrete hierarchical searchables. Given the variety of custom implementations of TreeModels, that's most probably possible only for the most simple.
    Some thoughts that came up in the discussions here and the other forums. In a concrete context, first measure if the traversal is slow: most in-memory models are lightning fast to traverse, nothing needs to be done except using the basic support.
    Only if the traversal is the bottleneck (as f.i. in the FileSystemModel implementations of SwingX) additional work is needed:
    - in a truly immutable and unmodifiable TreeModel we might get away with read-only access in a SwingWorker's background thread
    - the unmodifiable precondition is violated in lazy loading/deleting scenarios
    there might be a natural custom data structure which backs the model, which is effectively kind-of "detached" from the actual model which allows synchronization to that backing model (in both traversal and view model)
    - pass the actual search back to the database
    - use an wrapper on top of a given TreeModel which guarantees to access the underlying model on the EDT
    - "fake" background searching: actually do so in small-enough blocks on the EDT (f.i. in a Timer) so that the user doesn't notice any delay
    Whatever the technical option to a slow search, there's the same usability problem to solve: how to present the delay to the end user? And that's an entirely different story, probably even more context/requirement dependent :-)
    Thanks for all the valuable input!
    Jeanette

  • Uniqueness and document searches.

    I have an application where I need to enforce the uniqueness of an entire document structure. In a relational database, I'd create a unique index across all columns, but I realize that's not really possible using an xml database. Is there any way, other than a linear search across all documents, for me to enforce uniquness of an entire document? The document follows a pretty simple DOM structure, but the tree can be arbitrarily deep (although it tends not to be very deep in most cases)
    I was thinking of keeping a separate container as uniqueness index and keeping lists of documents by their MD5 hashes in it, but was hoping there was a more elegant way to go about it.
    Thanks,
    Daniel Peebles

    Hi Daniel,
    If you do go the hash route, you could consider storing that as a metadata field right in the XML document (perhaps not hashing on the metadata).
    You could then add a Berkeley DB XML Uniqueness Index on the (result of the hash) metadata.
    I'm assuming there is no single element in the document that could be a primary key since that would be a better choice.
    Ron

  • Dynamic 2-D map for A*search pathfinding problem

    The Problem is a Dynamic map (the user can change size of the map) that has obstacles(obstacle location determined by the user also) and the tile could only move to adjacent tiles(only 4 moves or less), Can anyone solve that in Java? (without visualization only sample code).

    basically im trying to match the value of one Map with the key of another. my thinking is that this requires me to loop through the first Map and for each value through the second Map and match up the key to it. heres my code so far:
    private static Map equiJoin(Map relation1, Map relation2) // The 2 maps
    Map resultRelation = new TreeMap();
    Iterator keys1Iterator = relation1.keySet().iterator();
    Iterator values1Iterator = relation1.values().iterator();
    while (keys1Iterator.hasNext() ) // Loop through relation1
    String primaryKey1 = (String) keys1Iterator.next();
    String foreignKey1 = (String) values1Iterator.next();
    List list = new ArrayList();
    Iterator keys2Iterator = relation2.keySet().iterator();
    Iterator values2Iterator = relation2.values().iterator();
    while (keys2Iterator.hasNext() ) // Loop through relation2
    String primaryKey2 = (String) keys2Iterator.next();
    String foreignKey2 = (String) values2Iterator.next();
    if(primaryKey2.equals(foreignKey1))
    list.add(foreignKey1);
    list.add(foreignKey2);
    resultRelation.put(primaryKey1, list);
    return resultRelation;
    im trying to come up with ways to make this faster, perhaps by turing the second while loop/linear search into a binary search. i do indeed think using the get(key) more would increase the speed but im still thinking about ways to implement that in the above code, the problem being that i dont know what key im looking for until i loop through it (if u know what i mean) =)
    many thanks.

  • Searches in java

    hey all I'm glad to be back in school because i get a chance to learn new things about programming. And with that comes annoying questions i usually post for the senior members.
    Here is what i dont understand about serching in java. What is better a linear search or a binary search? Also can you explain why it is better to use logofn to do searches?
    Thanks,
    MS

    hey all I'm glad to be back in school because i get a
    chance to learn new things about programming. And
    with that comes annoying questions i usually post for
    the senior members.
    Here is what i dont understand about serching in
    java. What is better a linear search or a binary
    search? Did you try googling for linear search and binary search? They are general CS concepts and not specific to Java.
    Also can you explain why it is better to use
    logofn to do searches?You mean O(log n)? Better than what? Certainly not better than O(1), but better than O(n! ^ 99). If you don't know why, google for big o notation.

Maybe you are looking for

  • At end of and sum key word is not working properly

    Hi All, I have a requirement in that I have to calculate at the end of each fiscal year. I am using this section of code, But in my output its only showing me the value of the last record, its not summing up at the end of fiscal year. This is my sect

  • How to have Having clause in Group by

    Hi All, While using aggregated function (max,min etc) on columns, the SQL generated automatically has the non aggregated columns in the group by clause. How to specify the Having condition ? select a , max(b) from t group by a having <condition> TIA.

  • I want to fix a Genius Mix as a playlist...How do I see track names in a Genius Mix?

    I want to fix a Genius Mix as a Playlist. How do I see track names behind a Genius Mix icon?

  • AutoUpdate + Air 3 + bunlde

    I've got the following error while updating my Air 3.0 application packaged with the bunlde option : An unexpected error occurred. Error# 16828 Here is my update.xml file : <?xml version="1.0" encoding="utf-8"?> <update xmlns="http://ns.adobe.com/air

  • Sales Productions error!!

    Guys did you know on the App Store, Numbers is in the Top Free categories BUT you still have to pay for it.... Apple are not advertising their products to the true value. They should give it to us for FREE if it in the Top Free categories!!