Binary Search Using String

I'm trying to perform a binary search on CDs stored in an arraylist but it will only work with the titles with no spaces (Such as Summertime & Heartless but not Dance Wiv Me). Is this a bug or will it simply not work with strings with a space in them? Also when it does work it will return the correct title but the artist and price aren't in the same arraylist index as the search value that was returned.
* Program to allow customers to purchase CDs from an online store
* @author (Martin Hutton)
* @version (24/05/2009)
import java.util.*;
public class CDs
    private Scanner input;
    private Scanner in;
    private Scanner sc;
    private CdList aCd;
    CDs()
        this.aCd = new CdList();
        this.menu();
    public void menu()
        int select = 5;
        do
            //Menu Display
            System.out.println("\n\t\t--== Main Menu ==---");
            System.out.println("\n\t\t1. View CDs");
            System.out.println("\n\t\t2. Purchase CDs");
            System.out.println("\n\t\t3. Search CDs");
            System.out.println("\n\t\t4. Sort CDs Titles");
            System.out.println("\n\t\t5. Exit");
            input = new Scanner(System.in);
            select = input.nextInt();
            switch (select)
                case 1 : this.view();
                break;
                case 2 : this.purchase();
                break;
                case 3 : this.search();
                break;
                case 4 : this.sort();
                break;
                case 5 : exit();
                break;
                default : System.out.println("Error! Incorrect menu selection!");
        while ( select != 5 );
    public void view()
        System.out.printf("\f");//Clear screen
        System.out.println("\t\t--== Avaiable CDs ==--");
        System.out.println("");
        int size = aCd.getTitle().size();
        //loop to display array date
        for ( int i = 0; i < size; i++ )
            System.out.println( "\t" + i + "\t" + aCd.getTitle().get(i)+ "\t\t\t" + aCd.getArtist().get(i) + "\t\t\t" + aCd.getPrice().get(i) + "\n");
    public void purchase()
       System.out.printf("\f");//Clear screen
       double arrayPurchase[] = new double [15];
       in = new Scanner(System.in);
       sc = new Scanner(System.in);
       double total = 0.0;
       int itemindex = 0;
       System.out.println("How many CDs would you like to purchase? ");
       int amountNumbers = in.nextInt();
       for(int i = 0; i< amountNumbers; i++)
           int q = itemindex;
           System.out.println("Please enter the CD number: ");
           q = in.nextInt();
           //aCd.getPrice().get(q);
           arrayPurchase[i] = aCd.getPrice().get(q);
           total += arrayPurchase;
System.out.println("\nThe total is: £" + total );
public void search()
System.out.println("\t\t--== Search CDs ==--\n");
System.out.println("Search for a CD: ");
String lc = input.next();
Collections.sort(aCd.getTitle());
int index = Collections.binarySearch(aCd.getTitle(),lc);
if ( index < 0 )
System.out.println("Sorry, CD not avaiable");
else
// System.out.println(aCd.getPrice().get(index));
System.out.println( index + aCd.getTitle().get(index) + "\t\t" + aCd.getArtist().get(index) + "\t\t" + aCd.getPrice().get(index));
this.aCd = new CdList();
public void sort()
System.out.println("\t\t-== Alphabetised CD Titles ==--\n");
Collections.sort(aCd.getTitle());
int size = aCd.getTitle().size();
for ( int i = 0; i < size; i++ )
System.out.println( "\t" + aCd.getTitle().get(i));
this.aCd = new CdList();
public void exit()
System.out.println("\nSystem shutting down...");
System.exit(0);
* Write a description of class CdList here.
* @author (your name)
* @version (a version number or a date)
import java.util.*;
public class CdList
//instance variables
private ArrayList<String> title;
private ArrayList<String> artist;
private ArrayList<Double> price;
public CdList()
//create instances
title = new ArrayList<String>();
artist = new ArrayList<String>();
price = new ArrayList<Double>();
//populate arrays
//add titles
title.add("Boom Boom Pow");
title.add("Summertime");
title.add("Number 1");
title.add("Shake It");
title.add("The Climb");
title.add("Not Fair");
title.add("Love Story");
title.add("Just Dance");
title.add("Poker Face");
title.add("Right Round");
title.add("Dance Wiv Me");
title.add("I'm Not Alone");
title.add("Hot 'n' Cold");
title.add("Viva La Vida");
title.add("Heartless");
//HEX codes
artist.add("Black Eyed Peas");
artist.add("Will Smith");
artist.add("Tinchy Stryder");
artist.add("Metro Station");
artist.add("Miley Cyrus");
artist.add("Lily Allen");
artist.add("Taylor Swift");
artist.add("Lady GaGa");
artist.add("Lady GaGa");
artist.add("Flo Rida");
artist.add("Dizzee Rascal");
artist.add("Calvin Harris");
artist.add("Katy Perry");
artist.add("ColdPlay");
artist.add("Kanye West");
//RGB Co-ods
price.add(0.99);
price.add(0.75);
price.add(1.99);
price.add(2.99);
price.add(2.99);
price.add(0.55);
price.add(2.75);
price.add(1.98);
price.add(1.25);
price.add(1.55);
price.add(0.99);
price.add(2.55);
price.add(0.55);
price.add(1.99);
price.add(0.99);
} //end of constructor
public ArrayList<String> getTitle()
return ( title );
} //end method
public ArrayList<String> getArtist()
return ( artist );
}//end method
public ArrayList<Double> getPrice()
return ( price );
}//end method

It sounds like you are having Scanner woes. Remember that the call:
select = input.nextInt();Reads the number inputted but not the rest of the line (the enter). Then the next call to readLine will read this.
Suggestion: do this, to read a number:
select = input.nextInt();
String restOfLine =input.nextLine(); //discard

Similar Messages

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

  • Binary search tree in java using a 2-d array

    Good day, i have been wrestling with this here question.
    i think it does not get any harder than this. What i have done so far is shown at the bottom.
    We want to use both Binary Search Tree and Single Linked lists data structures to store a text. Chaining
    techniques are used to store the lines of the text in which a word appears. Each node of the binary search
    tree contains four fields :
    (i) Word
    (ii) A pointer pointing to all the lines word appears in
    (iii) A pointer pointing to the subtree(left) containing all the words that appears in the text and are
    predecessors of word in lexicographic order.
    (iv) A pointer pointing to the subtree(right) containing all the words that appears in the text and are
    successors of word in lexicographic order.
    Given the following incomplete Java classes BinSrchTreeWordNode, TreeText, you are asked to complete
    three methods, InsertionBinSrchTree, CreateBinSrchTree and LinesWordInBinSrchTree. For
    simplicity we assume that the text is stored in a 2D array, a row of the array represents a line of the text.
    Each element in the single linked list is represented by a LineNode that contains a field Line which represents a line in which the word appears, a field next which contains the address of a LineNode representing the next line in which the word appears.
    public class TreeText{
    BinSrchTreeWordNode RootText = null;// pointer to the root of the tree
    String TextID; // Text Identification
    TreeText(String tID){TextID = tID;}
    void CreateBinSrchTree (TEXT text){...}
    void LinesWordInBinSrchTree(BinSrchTreeWordNode Node){...}
    public static void main(String[] args)
    TEXT univ = new TEXT(6,4);
    univ.textcont[0][0] = "Ukzn"; univ.textcont[0][1] ="Uct";
    univ.textcont[0][2] ="Wits";univ.textcont[0][3] ="Rhodes";
    univ.textcont[1][0] = "stellenbosch";
    univ.textcont[1][1] ="FreeState";
    univ.textcont[1][2] ="Johannesburg";
    univ.textcont[1][3] = "Pretoria" ;
    univ.textcont[2][0] ="Zululand";univ.textcont[2][1] ="NorthWest";
    univ.textcont[2][2] ="Limpopo";univ.textcont[2][3] ="Wsu";
    univ.textcont[3][0] ="NorthWest";univ.textcont[3][1] ="Limpopo";
    univ.textcont[3][2] ="Uct";univ.textcont[3][3] ="Ukzn";
    univ.textcont[4][0] ="Mit";univ.textcont[4][1] ="Havard";
    univ.textcont[4][2] ="Michigan";univ.textcont[4][3] ="Juissieu";
    univ.textcont[5][0] ="Cut";univ.textcont[5][1] ="Nmmu";
    univ.textcont[5][2] ="ManTech";univ.textcont[5][3] ="Oxford";
    // create a binary search tree (universities)
    // and insert words of text univ in it
    TreeText universities = new TreeText("Universities");
    universities.CreateBinSrchTree(univ);
    // List words Universities trees with their lines of appearance
    System.out.println();
    System.out.println(universities.TextID);
    System.out.println();
    universities.LinesWordInBinSrchTree(universities.RootText);
    public class BinSrchTreeWordNode {
    BinSrchTreeWordNode LeftTree = null; // precedent words
    String word;
    LineNode NextLineNode = null; // next line in
    // which word appears
    BinSrchTreeWordNode RightTree = null; // following words
    BinSrchTreeWordNode(String WordValue)
    {word = WordValue;} // creates a new node
    BinSrchTreeWordNode InsertionBinSrchTree
    (String w, int line, BinSrchTreeWordNode bst)
    public class LineNode{
    int Line; // line in which the word appears
    LineNode next = null;
    public class TEXT{
    int NBRLINES ; // number of lines
    int NBRCOLS; // number of columns
    String [][] textcont; // text content
    TEXT(int nl, int nc){textcont = new String[nl][nc];}
    The method InsertionBinSrchTree inserts a word (w) in the Binary search tree. The method Create-
    BinSrchTree creates a binary search tree by repeated calls to InsertionBinSrchTree to insert elements
    of text. The method LinesWordInBinSrchTree traverses the Binary search tree inorder and displays the
    words with the lines in which each appears.
    >>>>>>>>>>>>>>>>>>>>>>
    //InsertionBinTree is of type BinSearchTreeWordNode
    BinSrchTreeWordNode InsertionBinSrchTree(String w, int line,                                             BinSrchTreeWordNode bst)
    //First a check must be made to make sure that we are not trying to //insert a word into an empty tree. If tree is empty we just create a //new node.
         If (bst == NULL)
                   System.out.println(“Tree was empty”)
         For (int rows =0; rows <= 6; rows++)
                   For (int cols = 0; cols <= 4; cols++)
                        Textcont[i][j] = w

    What is the purpose of this thread? You are yet to ask a question... Such a waste of time...
    For future reference use CODE TAGS when posting code in a thread.
    But again have a think about how to convey a question to others instead of blabbering on about nothing.
    i think it does not get any harder than this.What is so difficult to understand. Google an implementation of a binary tree using a single array. Then you can integrate this into the required 2-dimension array for your linked list implemented as an array in your 2-d array.
    Mel

  • Storing strings in binary search tree

    On the below code I get: ClassCastException : java.lang.String . I am trying to build a binary search tree from a text file one word at a time. when I call this method below the first time it works fine, but on the second call it gets the error at the second if statement:
    getInfo() returns a String
        public void insertBST(Object o) {
            TreeNode p, q;
            TreeNode r = new TreeNode(o);
            if (root == null)
                root = r;
            else {
                p = root;
                q = root;
                while (q != null) {
                    p = q;
                    System.out.println(r.getInfo());
                    if (((TreeComparable)(r.getInfo())).compareTo((TreeComparable)(p.getInfo())) < 0)
                        q = p.getLeft();
                    else
                        q = p.getRight();
                if (((TreeComparable)(r.getInfo())).compareTo((TreeComparable)(p.getInfo())) < 0)
                    setLeftChild(p, r);
                else
                    setRightChild(p, r);               
       }------------ This is the code I use to call on the above function:
    public void readFromFile() {
            //int i = 1;
            while (fileScan.hasNext()) {
                    String buf = fileScan.next();
                   hash(buf);
                  if (table[tableIndex] == tableIndex) {
                     System.out.println("Same Omitted Word");
                    else{
                        obt.insertBST(buf);
                        System.out.println("Not an Omitted Word");
    public int hash(String s) {
                    sum = 0;
                        for(int i = 0; i< s.length(); i++)
                            sum += (int)s.charAt(i);
                        tableIndex = sum%TABLESIZE;
                            return tableIndex;
    -------------------Also, this interface is used by the insertBST function:
    public interface TreeComparable {
        public int compareTo(Object o);
        public void operate(Object o);
        public void visit();

    We got the inserBST() funtion from the instructor, it is in a ObjectBinaryTree class we should use to build the tree, also we received the TreeComparable interface which inserBST() uses from the instructor.
    One one part of the assigment it says"
    Note that while the TreeNode class is built to hold a generic Object, you'll be creating a Word class whose objects will be placed in the TreeNode's of the Binar search tree. Each Word object should provide the followinf fields:
    a reference to the word, an int to count the nomber of times it apears.
    Which I have not done, I'm simply passing the String as I read it from the file.
    Now, I'm thinking TreeComparable is acting as an Int object and is trying to cast a String which produces the error.
    Also, I have used this where the inserBST():
    public class ObjectBinaryTree implements TreeComparable {
    but then I get a message that it cant override one of the methods in TreeComparable.
    This is the rest of the class I'm using to implement the ObjectBinayTree class.
    public void readFromFile() {
            //int i = 1;
            while (fileScan.hasNext()) {
                    String buf = fileScan.next();
                    // System.out.println(buf);
                   hash(buf);
                   // System.out.println(tableIndex);
                  if (table[tableIndex] == tableIndex) {
                     //System.out.println("Same Omitted Word");
                    else{
                        //obt.insertBST(buf);
                        //System.out.println("Not an Omitted Word");
         public void makeHashTable() {
                    while (fileScan.hasNext()) {
                        String buf = fileScan.next();
                        hash(buf);
                        if (table[tableIndex] == 0)
                            table[tableIndex] = sum%TABLESIZE;
                    else{
                        do{
                            tableIndex++;
                    }while( table[tableIndex] != 0);
                            table[tableIndex] = sum % TABLESIZE;
                public int hash(String s) {
                    sum = 0;
                        for(int i = 0; i< s.length(); i++)
                            sum += (int)s.charAt(i);
                        tableIndex = sum%TABLESIZE;
                            return tableIndex;
         }

  • 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

  • How to search for upper/lower case using string using JAVA!!!?

    -I am trying to write a program that will examine each letter in the string and count how many time the upper-case letter 'E' appears, and how many times the lower-case letter 'e' appears.
    -I also have to use a JOptionPane.showMessageDialog() to tell the user how many upper and lower case e's were in the string.
    -This will be repeated until the user types the word "Stop". 
    please help if you can
    what i have so far:
    [code]
    public class Project0 {
    public static void main(String[] args) {
      String[] uppercase = {'E'};
      String[] lowercase = {'e'};
      String isOrIsNot, inputWord;
      while (true) {
       // This line asks the user for input by popping out a single window
       // with text input
       inputWord = JOptionPane.showInputDialog(null, "Please enter a sentence");
       if ( inputWord.equals("stop") )
        System.exit(0);
       // if the inputWord is contained within uppercase or
       // lowercase return true
       if (wordIsThere(inputWord, lowercase))
        isOrIsNot = "Number of lower case e's: ";
       if (wordIsThere(inputword, uppercase))
         isOrIsNot = "number of upper case e's: ";
       // Output to a JOptionPane window whether the word is on the list or not
       JOptionPane.showMessageDialog(null, "The word " + inputWord + " " + isOrIsNot + " on the list.");
    } //main
    public static boolean wordIsThere(String findMe, String[] theList) {
      for (int i=0; i<theList.length; ++i) {
       if (findMe.equals(theList[i])) return true;
      return false;
    } // wordIsThere
    } // class Lab4Program1
    [/code]

    So what is your question? Do you get any errors? If so, post them. What doesn't work?
    And crossposted: how to search for upper/lower case using string using JAVA!!!?

  • Reg : Read statement using Binary Search....

    I have an Internal Table as below
    Value           Description
    100               Product
    2008             Production Year
    05                 Production Month
    I am using Read statement with Binary Search for getting Production Month.
    Read table itab with key Description = 'Production Month' binary search.
    I am getting sy-subrc as 4 eventhough data is present in the table for Production Month.
    What may be the problem.

    Hi suganya,
    use
    sort table itab ascending by <production month>.    
    Read table itab with key description = <production month> binary search.
    Remember always, while using binary search always sort the internal table.
    Regards,
    Sakthi.

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

  • 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

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

  • Binary search tree - writing to a file in alphabetic order words from tree

    Hi
    I have written a program that will read a list of words from a file, insert these into a binary search tree, write words from the tree to another file, so that the resulting list contains words in ascending order. My input file Alpha1.txt contains the following contents in the order and format given (one word per line):
    Dawn
    Dave
    Mike
    Beth     
    David
    Gina
    Pat
    Cindy
    Sue
    My program is supposed to be producing an alphabetical list of these words in another file "final.txt".
    Instead it gives me the following list:
    Dave Beth David Gina Cindy Sue Pat Mike Dawn
    This is obviously wrong, right? My correct list in "final.txt" should be
    Beth Cindy Dave David Dawn Gina Mike Pat Sue
    I am not sure what is wrong with my code which I reproduce below:
    import java.io.*;
    import java.util.*;
    //read Java Developer's Almanac from exampledepot.com
    //Read this: http://en.wikipedia.org/wiki/Tree_traversal
    /**preorder(node)
      print node.value
      if node.left  ? null then preorder(node.left)
      if node.right ? null then preorder(node.right)
    public class AlphabeticBinarySortTree
         private static TreeNode root;
         private static TreeNode runner;
         static String[] alphaArray;
         static int alphaCounter;
         private static TreeNode alphaRunner;
         //Inner class
              private static class TreeNode
                   String word;
                   TreeNode left;
                   TreeNode right;
                   int count;
                   public TreeNode(String word)
                        this.word = word;
                        left = null;
                        right = null;
                   public void insertAll(TreeNode newNode)
                        if(newNode.word.compareTo(runner.word) < 1)
                             System.out.println("newNode.word = " + newNode.word);
                             if(runner.left == null)
                                  runner.left = newNode;
                                  runner = runner.left;
                             else
                                  insertAll(newNode);
                        else if(newNode.word.compareTo(runner.word) > 1)
                             System.out.println("newNode.word = " + newNode.word);
                             if(runner.right == null)
                                  runner.right = newNode;
                                  runner = runner.right;
                             else
                                  insertAll(newNode);
                        else
                             count++;
                   }// end method insertAll
                   // Recursively print words (with counts) in sorted order
                     public static void printInPreOrder(TreeNode root)
                             System.out.println(root.word + " ");
                             if(root.left != null)
                                   printInPreOrder(root.left);
                              if(root.right != null)
                                   printInPreOrder(root.right);
                       } //end method printInPreOrder()
                     //called from inside main
                    public static void arrangeInAscendingOrder(TreeNode root, PrintWriter pWriter)
                             if(root.left != null)
                                   arrangeInAscendingOrder(root.left, pWriter);
                             System.out.println();
                             System.out.println();
                             System.out.println(root.word + " ");
                             pWriter.write(root.word + " ");
                             if(root.right != null)
                                  arrangeInAscendingOrder(root.right, pWriter);
              }//end inner class TreeNode
         public AlphabeticBinarySortTree()
              root = null;
         //belong to the outer class
         public static void main(String[] args)
              System.out.println("This program reads text from a file that it will parse. ");
              System.out.println("In doing so, it will eliminate duplicate strings and ");
              System.out.println("pick up only unique strings.These strings will be in a ");
              System.out.println("stored in alphabetical order in a binary Search tree before they are ");
              System.out.println("written out to another text file in alphabetic order");
              //open the file for reading
              try
                   BufferedReader bReader = new BufferedReader(new FileReader("Alpha1.txt"));
                   String words;
                   int count;
                   //System.out.println("A test to inspect the contents of words: " + words);
                   //System.out.println("Words =" + words);
                   count = 0;
                   //why is there an endless loop when
                   //I use "while(str != null)
                   StringTokenizer st;
                   st = null;
                   //based on http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html
                   while ((words = bReader.readLine()) != null)
                        st = new StringTokenizer(words);
                       while(st.hasMoreTokens())
                            //shiffman.net/teaching/a2z/concordance
                            String token = st.nextToken();
                            System.out.println("Token = " +token);
                            AlphabeticBinarySortTree.initiateInsert(token);
                            //count the number of tokens in the string
                            count++;
                        }//end inner while
                   }//end outer while
                   System.out.println("Here are the contents of your tree:");
                   //System.out.println("before the call to print()");
                   print();
                   System.out.println("the no of words in the file is: " + count);
                   bReader.close();
              }//end of try
              catch(IOException exception)
                   exception.printStackTrace();
                   /**try
                             FileWriter fWriter = new FileWriter("final.txt");
                             BufferedWriter bWriter = new BufferedWriter(fWriter);
                             PrintWriter pWriter = new PrintWriter(bWriter);
                   catch(IOExcepion exception)
                        exception.printStackTrace();
         } // end main here
         //this method belongs to the outer class
         static void initiateInsert(String word)
              //TreeNode is also static by the way
              TreeNode newNode = new TreeNode(word);
              if(root == null)
                   root = newNode;
                   System.out.println("root.word = " + root.word);
                   runner = root;
              else
                   runner.insertAll(newNode);
         // Start the recursive traversing of the tree
            //without the access specifier 'static'
            //I would get the following error message
            //AlphabeticBinarySortTree.java:119: non-static method print() cannot be referenced from a static context
            public static void print()
                //System.out.println("**********AM I INSIDE THE PRINT() METHOD? ********");
               if (root != null)
                    //System.out.println("++++++++ AM I INSIDE THE IF BLOCK OF THE PRINT() METHOD? +++++++");
                    //System.out.println("Inside THE IF BLOCK OF print() BUT BEFORE THE CALL TO printInPreOrder(),root.word = " + root.word);
                  AlphabeticBinarySortTree.TreeNode.printInPreOrder(root);
                  //open the file for writing
                              try
                                             FileWriter fWriter = new FileWriter("final.txt");
                                             BufferedWriter bWriter = new BufferedWriter(fWriter);
                                             PrintWriter pWriter = new PrintWriter(bWriter);
                                             AlphabeticBinarySortTree.TreeNode.arrangeInAscendingOrder(root, pWriter);
                                          pWriter.close();
                              catch(IOException eException)
                                   eException.printStackTrace();
               }//end of if block
            } // end of method print
    }//end outer enclosing class here--------
    All help is highly appreciated. Thanks for your time and consideration.

    You suggest that I do away with the inner class
    then?Absolutely. In fact I strongly suggest this. You are learning how to code and need to do things cleanly and in small steps. That means first creating your Node class and making sure it works. Then creating your Tree class, and making sure it works. In fact I would load the Strings into the Tree class first directly and testing things before even thinking about reading to and from files. Only then should you implement the file input and output steps.
    The key here is that you don't go on to the next step until you're reasonably sure that your current code works. Remember, it's MUCH easier to code than to debug.

  • Creating A Binary search algorithm !!!! URGENT HELP

    hi ..
    i;m currently tryin to create a binary search algorithm ..
    the user should be able to input the size of the array
    and also the key that he would like to find.
    it also has to have to ability to measure the run time of the algorithm.. it how long it too the algorithm to search through the array and find they key..
    i have created 3 classes
    the first class is the binary search class
    which is the mathamatical side of things
    the second class is the Array
    this creates an array selection a random first number
    and then incrementing from there, so that its a sorted array
    the third class is the binary search class
    which is my main class.
    this class should take the users input
    and pass it to the array
    and the binary seach accordingly
    it should also measure the running time, from when it passes the array
    to the binary search class
    i am having a really hard time creating this last class.
    i have created the other 2 successfully
    the codes for the binary search class is as follows
    public class BinarySearch
         static int binSearch(int[] array, int val)
             // setting the start and the end of the array
              int low = 0, high = array.length;
              //While loop
              while(low <= high) {
              // How to find the mid point      
                  int mid = (low + high)/2;
                   // if the mid point is the value return the value
                  if(array[mid] == val) {
                        return mid;
                   // if the value is smaller than the mid point
                   // go search the left half
                   } else if(array[mid] > val) {
                        high = mid - 1;
                   //if the value is greater then the mid point
                   // go search the right half
                   } else if(array[mid] < val) {
                        low = mid + 1;
              // if value is not found return nothing
              return -1;
    }and the code for the Array class is as follows
    import java.util.Random;
    public class RandomSortedArray
        public int[] createArray(int length)
            // construct array of given length
            int[] ary = new int[length];
            // create random number generator
            Random r = new Random();
            // current element of the array; used in the loop below.  Starts at
            // -1 so that the first element of the array CAN be a 0
            int val = -1;
           for( int i = 0; i < length; i++)
                val += 1 + r.nextInt(10);
                ary[i] = val;
            return ary;
    }can some pne please help me create my binarysearchTest class.
    as i mentioned before
    it has to take the users input for the array size
    and the users input for the value that they want to find
    also needs to measure the running time
    thanks for all ur help in advance

    import java.util.*;
    public class AlgorithmTest
         public static void main(String args[])
             long StartTime, EndTime, ElapsedTime;
             System.out.println ("Testing algorithm");
             // Save the time before the algorithm run
             StartTime = System.nanoTime();
             // Run the algorithm
             SelectionSortTest1();
             // Save the time after the run
             EndTime = System.nanoTime();
             // Calculate the difference
             ElapsedTime = EndTime- StartTime;
             // Print it out
             System.out.println("The algorithm took " + ElapsedTime + "nanoseconds to run.");
        }this is the code i managed to work up for measuring the time..
    how would i include it into the main BinarysearchTest Class

  • 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

  • Poor font display in Acrobat X

    When I view many PDF files in Acrobat Pro X (10.1.9) in Windows 7, the font displays poorly: The same file appears fine in the Firefox viewer: Any idea how I can fix the issue?

  • Autoplaying a website intro slideshow in Flash Catalyst

    I was wondering if anyone knew a way, in Flash Catalyst, to create a Website Introduction slideshow as seen in the following websites: http://www.infinityward.com/ http://www.spinxwebdesign.com/ http://www.whitehouse.gov/ The goal is to create 5 or 6

  • JPA persist() or merge()

    Hi All, I would like to get clarification between using JPA persist() and merge() where there is a OneToMany EMPLOYEE table unidirectionally joint to ManyToOne TELEPHONE table. The code snippet for OneToMany Employee.java entity object is as follows:

  • SMTP service is not starting

    on my Maverik Server 3.1.1 my SMTP service is not starting. IMAP is OK when i use: "sudo serveradmin fullstatus mail" I get : mail:startedTime = "2014-03-26 19:11:38 +0000" mail:setStateVersion = 1 mail:state = "STARTING" mail:protocolsArray:_array_i

  • POST data without navigating to page

    Hi, I need to POST some data collected in a form to an ASP page hosted by another person. How do I do this without navigating to that ASP page, so I can remain within my own website ? Thanks for the help, M