Arrays,bubblesort, and binary search

Hi I need help I have been working on this homework assignment for the past week and I can't seem to get it so if anyone can help me to figure out what is wrong I would reall grateful. Thanks ahead of time for the help.
Here is what is required for the assignment and also the errors I am getting.
Thanks!
Write a program that sorts an integer array in ascending order and checks whether an integer entered by user is in the array or not. Please follow the following steps to complete the assignment:
1. Declare and create a one-dimensional array consisting of 20 integers.
2. Read 20 integers from the user to initialize the array. Use input dialog box and repetition statement.
3. Build an output string containing the content of the array.
4. Sort the array in ascending order using bubbleSort( ) and swap( ) methods. Then, append the content of the sorted array to the output string.
5. Read an integer search key from the user;
6. Use binarySearch( ) method to check whether the search key is in the array or not. Then, append the search result to the output string.
7. Display the output string in a message box.
Here is my code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SortSearch {
public static void main (String args[])
String input, ouput;
int key;
int index;
int[] array=new int [20];
input=JOptionPane.showInputDialog("Enter 20 Numbers");
for(int counter=0; counter<array.length; counter++)
output+=counter+"\t"+array[counter]+"\n";
array(counter)=Integer.parseInt(input);
JTextArea inputArea=new JTextArea();
outputArea.setText(output);
public void bubblesort(int array2[] )
for(int pass=1; pass<array2.length; pass++){
for(int element=0; element<array2.length-1; element++){
if(array2[element]>array2[element+1])
swap(array2, element, element+1);
public void swap(int array3[], int first, int second)
int hold;
hold=array3[first];
array3[first]=array3[second];
array3[second]=hold;
public void actionPerformed(ActionEvent actionEvent)
String searchKey=actionEvent.getActionCommand();
int element=binarySearch(array, Integer.parseInt(searchKey) );
if(element!=-1)
output.setText("Found value in element " + element);
else
output.setText("Value not found ");
public int binary search(iny array2[], int key)
int low=0;
int high=array2.length-1;
int middle;
while(low<=high){
middle=(low + high)/2;
buildOutput(array2, low, middle, high);
if(key==array[middle] )
return middle;
else if(key<array[middle] )
high=middle-1;
else
low=middle+1
return-1
JOptionPane.showMessageDialog(null, outputArea);
System.exit(0);
} //end main
} //end class
Here is my errors
C:\java>javac SortSearch.java
SortSearch.java:27: illegal start of expression
public void bubblesort(int array2[] )
^
SortSearch.java:20: cannot resolve symbol
symbol : variable output
location: class SortSearch
output+=counter+"\t"+array[counter]+"\n";
^
SortSearch.java:22: cannot resolve symbol
symbol : variable counter
location: class SortSearch
array(counter)=Integer.parseInt(input);
^
SortSearch.java:25: cannot resolve symbol
symbol : variable output
location: class SortSearch
outputArea.setText(output);
^
SortSearch.java:25: cannot resolve symbol
symbol : variable outputArea
location: class SortSearch
outputArea.setText(output);
^
5 errors

I am still having problems.
Here is my code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SortSearch {
      public static void main (String args[]){
      String input, output;
      int key;
      int index;
      int[] array=new int [20];
      input=JOptionPane.showInputDialog("Enter 20 Numbers");
      for(int counter=0; counter<array.length; counter++)
        array(counter)=Integer.parseInt(input);
      JTextArea outputArea=new JTextArea();
      outputArea.setText(output);
        public void bubblesort(int array2[] )
          for(int pass=1; pass<array2.length; pass++){
            for(int element=0; element<array2.length-1; element++){
              if(array2[element]>array2[element+1]) 
                swap(array2, element, element+1);
            }  //end inner for
          }  //end outer for
        }  //end bubblesort 
        public void swap(int array3[], int first, int second)
          int hold;
          hold=array3[first];
          array3[first]=array3[second];
          array3[second]=hold;
        }  //end swap
        public void actionPerformed(ActionEvent actionEvent)
          String searchKey=actionEvent.getActionCommand();
          int element=binarySearch(array, Integer.parseInt(searchKey) );
          if(element!=-1)
            outputArea.setText("Found value in element " + element);
          else
            outputArea.setText("Value not found ");
        }  //end actionperformed
        JOptionPane.showMessageDialog(null, outputArea,"Comparisons");       
}  //end classHere is my errors
C:\java>javac SortSearch.java
SortSearch.java:57: <identifier> expected
JOptionPane.showMessageDialog(null, outputArea,"Comparisons");
^
SortSearch.java:57: cannot resolve symbol
symbol : class showMessageDialog
location: class javax.swing.JOptionPane
JOptionPane.showMessageDialog(null, outputArea,"Comparisons");
^
SortSearch.java:19: cannot resolve symbol
symbol : method array (int)
location: class SortSearch
array(counter)=Integer.parseInt(input);
^
SortSearch.java:49: cannot resolve symbol
symbol : variable array
location: class SortSearch
int element=binarySearch(array, Integer.parseInt(searchKey) );
^
SortSearch.java:52: cannot resolve symbol
symbol : variable outputArea
location: class SortSearch
outputArea.setText("Found value in element " + element);
^
SortSearch.java:54: cannot resolve symbol
symbol : variable outputArea
location: class SortSearch
outputArea.setText("Value not found ");
^
6 errors
Thanks ahead of time I still don't understand the stuff so I sometime don't understand what my errors are telling me so that is why I ask for your help so that maybe it will help make sense.

Similar Messages

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

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

  • Read table and binary search

    Hi all,
    I have a simple query regarding read int_tab with binary search.
    Why reading  internal table with binary search fails if it is sorted in descending order table must be sorted in ascending order?
    I check fo the algorithm of binary search, it does not talk about sort order. As far as my understanding goes binary search only require sorted table but while reading table in SAP it has to be sorted in ascending order!!

    By default binary search assumes that the sort order is ASCENDING.
    If you sort the list in descending and then try to binary search your quires will fail. Look at an example:
    Let the descending order internal table as:
    Field1      Field2
    Sam        50000
    John       34786
    Boob      54321
    Alice       12345
    When you do binary search with key = 'Sam' then it will directly go to 2nd and 3rd records for comparision. The binary search algorithm compares 'Sam' with 'John' and it concludes that 'Sam' is greater than 'John' and it will continue to look downward into the internal table. And when it reaches the end of the internal table then the value of SY-TABIX = 5 and SY-SUBRC = 8 (Key is greater than the all).
    And if you do binary search with key = 'Alice' then the binary search algorithm compares 'Alice' with 'John' and it concludes that 'Alice' is lower than 'John' and it will continue to look upward into the internal table. And when it reaches above the first record in internal table then the value of SY-TABIX = 1 and SY-SUBRC = 4 (points to the next largest entry).
    The only correct result you will get is when you execute statement with key='John' (In this particular case) . SY-TABIX = 2 and SY-SUBRC = 0. I think you got this binary search algorithm.

  • 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

  • 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

  • Sequential vs binary search

    hello:
    i am trying to know how to find the theoretical running time for both the sequential and binary search algorithms. i have written a program that determines the timing when running on my pc, however, i would like to compare these results against the ones ran via the program i have written.
    thanks for any tips,
    java40

    I'm not sure what you're asking either.
    It sounds like you're asking how to determine the time required to run the search. You can't determine that precisely. What you can do is determine the "big O" time, which doesn't tell you how fast it will run for a given input set, but does give you an idea of how fast the running time grows as the input size grows.
    As for how you determine the big-O time, as already mentioned, that's well documented in textbooks, google, wikipedia...

  • 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

  • Java binary search and insert

    I'm currently writing a program which is an appointment book. I currently have 4 classes and at the minute it can sort the array and print it out. I'm stuck at binary search and inserting a new appointment record. I will include the classes which i have got.
    Appointment
       import java.util.*;
       import java.io.*;
       import java.util.Scanner;
        class Appointment implements Comparable
          private String description;
          private int day;
          private int month;
          private int year;
          private String startTime;
          private String endTime;
          protected static Scanner keyboard = new Scanner(System.in);     
           public Appointment()
             description = "";
             day = 0;
             month = 0;;
             year = 0;;
             startTime = "";
             endTime = "";
           public Appointment(String appDesc, int appDay, int appMonth, int appYear, String appStartTime, String appEndTime)
             description = appDesc;
             day = appDay;
             month = appMonth;
             year = appYear;
             startTime = appStartTime;
             endTime = appEndTime;
           public void display()      
             System.out.print("  Description: " + description);
             System.out.print(", Date: " + day + "/" +month+ "/" +year);
             System.out.println(", Start Time: " + startTime);
             System.out.println(", End Time: " + endTime);
           public void setDay(int day)
          { this.day = day; }
           public int getDay()     
             return day; }
           public void setMonth(int month)
          { this.month = month; }
           public int getMonth()     
             return month; }
           public void setYear(int year)
          { this.year = year; }
           public int getYear()
             return year; }
           public int compareTo(Object obj)
             if (obj instanceof Appointment)
                Appointment appt = (Appointment) obj;
                if (this.day > appt.getDay())
                   return 1;
                else if (this.day < appt.getDay());
                return -1;
             return 0;
           public String toString() {
             StringBuffer buffer = new StringBuffer();
             buffer.append("Description: " + description);
             buffer.append(", Date: " + day + "/" +month+ "/" +year);
             buffer.append(", Start Time: " + startTime);
             buffer.append(", End Time: " + endTime);
             return buffer.toString();
           public void read(){
             System.out.print("Description : ");String descIn=keyboard.next();
             System.out.print("Day : ");int dayIn=keyboard.nextInt();
             System.out.print("Month : ");int monthIn=keyboard.nextInt();
             System.out.print("Year : ");int yearIn=keyboard.nextInt();
             System.out.print("Start Time : ");String startIn=keyboard.next();
             System.out.print("End Time : ");String endIn=keyboard.next();
             boolean goodInput = false;
             do{          
                try{
                   setDay(dayIn);
                   setMonth(monthIn);
                   setYear(yearIn);
                   goodInput = true;
                    catch(IllegalArgumentException e){
                      System.out.println("INVALID ARGUMENT PASSED FOR day or month or year");
                      System.out.println(e);
                      System.out.print("RE-ENTER VALID ARGUMENT FOR DAY : ");dayIn=keyboard.nextInt();
                      System.out.print("RE-ENTER VALID ARGUMENT FOR MONTH : ");monthIn=keyboard.nextInt();
                      System.out.print("RE-ENTER VALID ARGUMENT FOR YEAR : ");yearIn=keyboard.nextInt();                                        
             }while(!goodInput);
       }

    Array
    import java.util.*;
    class Array
         private Appointment[] app;
         private int nElems;
         Appointment tempApp;
         public Array(int max)
              app = new Appointment[max];
              nElems = 0;
         public Array(String desc, int day, int month, int year, String sTime, String eTime)
              app = new Appointment[100];
              nElems = 0;
       public int size()
          { return nElems; }
         void add(){
              Appointment appointmentToAdd = new Appointment();
              // Read its details
              appointmentToAdd.read();
              // And add it to the studentList
              //app[nElems].add(appointmentToAdd);
         public void add(String desc, int day, int month, int year, String sTime, String eTime)
            app[nElems] = new Appointment(desc, day, month, year, sTime, eTime);
            nElems++;             // increment size
              Appointment appointmentToAdd = new Appointment(desc, day, month, year, sTime, eTime);
              // And add it to the studentList
              //app[nElems].add(appointmentToAdd);
          public void insert(Appointment tempApp) {
        int j;
        for (j = 0; j < nElems; j++)
          // find where it goes
          if (app[j] > tempApp) // (linear search)
            break;
        for (int k = nElems; k > j; k--)
          // move bigger ones up
          app[k] = app[k - 1];
        app[j] = tempApp; // insert it
        nElems++; // increment size
       public void display()       // displays array contents
            for(int j=0; j<nElems; j++)    // for each element,
              app[j].display();     // display it
            System.out.println("");
         public void insertionSort()
       int in, out;
       for(out=1; out<nElems; out++) // out is dividing line
         Appointment temp = app[out];    // remove marked person
         in = out;          // start shifting at out
         while(in>0 &&        // until smaller one found,
            app[in-1].getMonth().compareTo(temp.getMonth())>0)
          app[in] = app[in-1];     // shift item to the right
          --in;          // go left one position
         app[in] = temp;        // insert marked item
         } // end for
       } // end insertionSort()
    }Menu
    import java.util.*;
    class Menu{
       private static Scanner keyboard = new Scanner(System.in);
       int option;
         Menu(){
            option=0;
         void display(){
              // Clear the screen
            System.out.println("\n1 Display");
              System.out.println("\n2 Insert");          
              System.out.println("3 Quit");          
         int readOption(){
            System.out.print("Enter Option [1|2|3] : ");
              option=keyboard.nextInt();
              return option;
    }Tester
       import java.util.*;
       import java.util.Arrays;
        class ObjectSortApp
           public static void main(String[] args)
                   int maxSize = 100;
                   Array arr;
                   arr = new Array(maxSize)
                   Appointment app1 = new Appointment("College Closed", 30, 4, 2009, "09:30", "05:30");;
                   Appointment app2 = new Appointment("Assignment Due", 25, 4, 2009, "09:30", "05:30");
             Appointment app3 = new Appointment("College Closed", 17, 4, 2009, "09:30", "05:30");
             Appointment app4 = new Appointment("Easter Break", 9, 4, 2009, "01:30", "05:30");
             Appointment app5 = new Appointment("College Opens", 15, 4, 2009, "09:30", "05:30");
             Appointment app6 = new Appointment("Assignment Due", 12, 4, 2009, "09:30", "05:30");
             Appointment app7 = new Appointment("Exams Begin", 11, 4, 2009, "09:30", "05:30");
                //To sort them we create an array which is passed to the Arrays.sort()
            //method.
            Appointment[] appArray = new Appointment[] {app1, app2, app3, app4, app5, app6, app7};
             System.out.println("Before sorting:");
            //Print out the unsorted array
            for (Appointment app : appArray)
                System.out.println(app.toString()); 
                Arrays.sort(appArray);
             //arr.insertionSort();      // insertion-sort them
             System.out.println("\n\nAfter sorting:");               
            //Print out the sorted array
            for (Appointment app : appArray)
                System.out.println(app.toString());
              Menu appMenu = new Menu();
              int chosenOption;
              do{
                 appMenu.display();
                   chosenOption=appMenu.readOption();
                   for (Appointment app : appArray)
                   switch(chosenOption){
                      case 1 : app.display(); break;
                        case 2 : arr.add(); break;
                        default:;
              }while(chosenOption != 3);    
          } // end main()
       } // end class ObjectSortApp

  • 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

  • Java question help (applying binary search)

    please show me how do i apply a binary search inside this program where i can use the binary serach to search for the book author or book title
    // objectSort.java
    // demonstrates sorting objects (uses bubble sort)
    // to run this program: C>java libmainsys
    class libary
    private String booktitle;
    private String bookauthor;
    private String publisher;
    private int yearpublished;
    private int edition;
    private int nofcop;
    public libary(String title, String author, String pub, int yrpub, int edt, int nfcp)
    {                // constructor
    booktitle = title;
    bookauthor = author;
    publisher = pub;
    yearpublished = yrpub;
    edition = edt;
    nofcop = nfcp;
    public void displaylibary()
    System.out.print(" Book Title: " + booktitle);
    System.out.print(", Book Author: " + bookauthor);
    System.out.print(", Book Publisher: " + publisher);
    System.out.print(", Year Published: " + yearpublished);
    System.out.print(", Edition: " + edition);
    System.out.println(",No Of Copies : " + nofcop);
    public String getLast() // get title
    { return booktitle; }
    } // end class libary
    class ArrayInOb
    private libary[] nfcp; // ref to array ypub
    private int nElems; // number of data items
    public ArrayInOb(int max) // constructor
    nfcp = new libary[max]; // create the array
    nElems = 0; // no items yet
    // put libary into array
    public void insert(String title, String author, String pub, int yrpub, int edt, int nofcop)
    nfcp[nElems] = new libary(title, author, pub, yrpub, edt, nofcop);
    nElems++; // increment size
    public void display() // displays array contents
    for(int j=0; j<nElems; j++) // for each element,
    nfcp[j].displaylibary(); // display it
    System.out.println("");
    public void bubbleSort()
    int i, j;
    libary temp;
    for (i = nElems-1; i >= 0; i--)
    for (j = 1; j <= i; j++)
    if (nfcp[j-1].getLast().compareTo(nfcp[j].getLast())>0)
    temp = nfcp[j-1];
    nfcp[j-1] = nfcp[j];
    nfcp[j] = temp;
    } // end class ArrayInOb
    class libmainsys
    public static void main(String[] args)
    int maxSize = 1000; // array size
    ArrayInOb arr; // reference to array
    arr = new ArrayInOb(maxSize); // create the array
    arr.insert("Java_how__to_program", "Patty_John", "Deitel", 2001, 1, 430);
    arr.insert("System_Design", "Dexter_Smith", "Thomson", 2002, 3, 450);
    arr.insert("Program_Design", "Lorraine_Paul", "About", 1996, 2, 196);
    arr.insert("Computer_Architecture", "Paul_Andrew","Dzone", 2006, 5, 199);
    arr.insert("Visual_Basic_How_To_ Program", "Tom_Jones", "Jeffereson_publication", 2007, 4, 207);
    arr.insert("Information_ Management", "William_Peter", "Mcgraw_Hill", 1995, 3, 204);
    arr.insert("Sofware_ Application", "Henry_Sam", "Pearson", 2001, 6, 278);
    arr.insert("English", "Samantha_Julia", "James_Hill", 2005, 1, 200);
    arr.insert("Web_Publishing", "Audrey_Cynthia", "Surg", 2004, 3, 201);
    arr.insert("Human_Computer_Interaction", "Tony_Edward", "Telde", 2003, 3, 199);
    System.out.println("Before sorting:");
    arr.display(); // display items
    arr.bubbleSort(); // insertion-sort them
    System.out.println("After sorting:");
    arr.display(); // display them again
    } // end main()
    } // end class libmainsys

    I see you haven't worked out bubbleSort either. Since binary search only works on sorted arrays, I suggest you start there. Do you have the algorithms somewhere?
    If you really need to be able to search using either author or title, I suggest you create 2 Comparators that compare using the desired property. Comparator is just an interface that defines methods to compare 2 objects. You have to write your own implementation of it to compare library objects. You'll always have to sort and search using the same Comparator.

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

  • Binary search tree errors

    MORE A CRY FOR HELP THEN A QUESTION-THANKS!
    I'm having some diffucilites debugging errors produced by my binary search tree class. Spent alot of time trying correct them but just doesn't seem to be working for me :|!. I'm working with two main classes BinaryNode and BinarySearchTree.
    class BinaryNode<AnyType> extends BinarySearchTree
        // Constructor
        BinaryNode(AnyType theElement)
            element = theElement;
            left = right = null;
          // Data; accessible by other package routines
        AnyType             element;  // The data in the node
        BinaryNode<AnyType> left;     // Left child
        BinaryNode<AnyType> right;    // Right child
    public class BinarySearchTree<AnyType extends Comparable<? super AnyType>>
          /** The tree root. */
        protected BinaryNode<AnyType> root;
        private int[] unsorted = new int[] {3,6,7,2,1};
         * Construct the tree.
        public BinarySearchTree()
         root = null;
         * Insert into the tree.
         * @param x the item to insert.
         * @throws DuplicateItemException if x is already present.
        public void insert(AnyType x)
            root = insert(x, root);
         * Remove from the tree..
         * @param x the item to remove.
         * @throws ItemNotFoundException if x is not found.
        public void remove(AnyType x)
            root = remove(x, root);
         * Remove minimum item from the tree.
         * @throws ItemNotFoundException if tree is empty.
        public void removeMin()
            root = removeMin(root);
         * Find the smallest item in the tree.
         * @return smallest item or null if empty.
        public BinaryNode<AnyType> findMin()
         //uses a helpler method that iterates over the left hand of the binary tree
            return(findMin(root));
         * Find the largest item in the tree.
         * @return the largest item or null if empty.
        public BinaryNode<AnyType> findMax()
            return (findMax(root));
         * Find an item in the tree.
         * @param x the item to search for.
         * @return the matching item or null if not found.
        public AnyType find(AnyType x)
            return elementAt(find(x,root));
         * Make the tree logically empty.
        public void makeEmpty()
            root = null;
         * Test if the tree is logically empty.
         * @return true if empty, false otherwise.
        public boolean isEmpty()
            return root == null;
         * Internal method to get element field.
         * @param t the node.
         * @return the element field or null if t is null.
        public AnyType elementAt(BinaryNode<AnyType> t)
            return t == null ? null : t.element;
         * Internal method to insert into a subtree.
         * @param x the item to insert.
         * @param t the node that roots the tree.
         * @return the new root.
         * @throws DuplicateItemException if x is already present.
        protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> t)
            if(t == null) {
                t = new BinaryNode<AnyType>(x);
            else if(x.compareTo(t.element) < 0) {
                t.left = insert(x, t.left);
            else if(x.compareTo(t.element) > 0 ) {
                t.right = insert(x, t.right);
            else {
                throw new DuplicateItemException(x.toString());  // Duplicate
            return t;
         * Internal method to remove from a subtree.
         * @param x the item to remove.
         * @param t the node that roots the tree.
         * @return the new root.
         * @throws ItemNotFoundException if x is not found.
        protected BinaryNode<AnyType> remove(AnyType x, BinaryNode<AnyType> t)
            if(t == null) {
                throw new ItemNotFoundException(x.toString());
            if(x.compareTo(t.element) < 0) {
                t.left = remove(x,t.left);
            else if(x.compareTo(t.element) > 0) {
                t.right = remove(x, t.right);
            else if(t.left != null && t.right != null) // Two children
                t.element = findMin(t.right).element;
                t.right = removeMin(t.right);
            else {
                t = (t.left != null) ? t.left : t.right;
            return t;
         * Internal method to remove minimum item from a subtree.
         * @param t the node that roots the tree.
         * @return the new root.
         * @throws ItemNotFoundException if t is empty.
        protected BinaryNode<AnyType> removeMin(BinaryNode<AnyType> t)
            if(t == null) {
                throw new ItemNotFoundException();
            else if(t.left != null) {
                t.left = removeMin(t.left);
                return t;
            else {
                return t.right;
        * Given a non-empty binary search tree,
        * return the minimum data value found in that tree.
        * Note that the entire tree does not need to be searched.
        * @param t the node that roots the tree.
        * @return node containing the smallest item.
        protected BinaryNode<AnyType> findMin(BinaryNode<AnyType> t)
            if(t != null) {
                while(t.left != null) {
                    t = t.left;
            return t; //the smallest value
         * Internal method to find the largest item in a subtree.
         * @param t the node that roots the tree.
         * @return node containing the largest item.
        protected BinaryNode<AnyType> findMax(BinaryNode<AnyType> t)
            if(t != null) {
                while(t.right != null) {
                    t = t.right;
            return t; //the largest value
         * Internal method to find an item in a subtree.
         * @param x is item to search for.
         * @param t the node that roots the tree.
         * @return node containing the matched item.
        private BinaryNode<AnyType> find(AnyType x, BinaryNode<AnyType> t)
            while(t != null) {
                if(x.compareTo(t.element) < 0) {
                    t = t.left;
                else if(x.compareTo(t.element) > 0) {
                    t = t.right;
                else {
                    return t;    // Match
            return null;         // Not found
        public void betweenTraverse() {
         betweenTraverse(root);
        * Given two integers,
        * print all the values in the tree which are between these two numbers
        * in ascending order.
        * @param t is BinaryTree to search through
        * @param a is min integer to start print from
        * @param b is max integer to keep integer print between
        private void betweenTraverse(BinaryNode<AnyType> t)
         //enter samllest vaule
         int a = System.in.read();
         //enter largetest vaule
         int b = System.in.read();
         if (t != null) {
             inorderTraverse(t.left);
             if(t.elementAt(t) >a && t.elementAt(t) < b) { //LINE 274 with error
              System.out.println(t.elementAt(t));
             inorderTraverse(t.right);
        * Given an array of unsorted integers 
        * adds add the these elements of unsorted as nodes
        * to an initially empty binary search tree
        * @param x is array which it element to be added to a binary tree
        public BinarySearchTree<Integer> numberstoTree(int[] x)
         BinarySearchTree<Integer> treeOne = new BinarySearchTree<Integer>();
         Arrays.sort(x);
         for (int i = 0 ; i < x.length ; i++) {
                int j = x;
         treeOne.insert(j);     
         treeOne.inorderTraverse();
         return treeOne;
    public void inorderTraverse() {
         inorderTraverse(root);
    private void inorderTraverse(BinaryNode<AnyType> t) {
         if (t != null) {
         inorderTraverse(t.left);
         System.out.println(t.elementAt(t));
         inorderTraverse(t.right);
    // Test program
    public static void main(String[] args)
    BinarySearchTree<Integer> t = new BinarySearchTree<Integer>();
    final int NUMS = 4000;
    final int GAP = 37;
    System.out.println("Checking... (no more output means success)");
    for( int i = GAP; i != 0; i = ( i + GAP ) % NUMS ) {
    t.insert(i);
    for(int i = 1; i < NUMS; i += 2) {
    t.remove(i);
    if(t.findMin().elementAt(t) != 2 || t.findMax().elementAt(t) != NUMS - 2) { //LINE 332 with error
    System.out.println("FindMin or FindMax error!");
    for(int i = 2; i < NUMS; i += 2) {
         if( t.find(i) != i) {
    System.out.println("Find error1!");
    for(int i = 1; i < NUMS; i += 2) {
    if(t.find(i) != null) {
    System.out.println("Find error2!");
    }I getting these errors:BinarySearchTree.java:274: operator > cannot be applied to java.lang.Comparable,int
         if(t.elementAt(t) >a && t.elementAt(t) < b) {
    ^
    BinarySearchTree.java:274: operator < cannot be applied to java.lang.Comparable,int
         if(t.elementAt(t) >a && t.elementAt(t) < b) {
    ^
    BinarySearchTree.java:332: elementAt(BinaryNode) in BinarySearchTree cannot be applied to (BinarySearchTree<java.lang.Integer>)
    if(t.findMin().elementAt(t) != 2 || t.findMax().elementAt(t) != NUMS - 2) {
    ^
    BinarySearchTree.java:332: cannot find symbol
    symbol : method elementAt(BinarySearchTree<java.lang.Integer>)
    location: class java.lang.Integer
    if(t.findMin().elementAt(t) != 2 || t.findMax().elementAt(t) != NUMS - 2) {
    ^ I've tried to change the method return types, to integer, AnyType but still producing more or same amount of errors, any help debugging this would be so helpful!.
    Thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    So i've tried to re implement the static statements. i.e
    if(t.findMin().compareTo(t.elementAt(t.root)) != 2 || t.findMax().compareTo(t.elementAt(t.root)) != NUMS - 2) {
                System.out.println("FindMin or FindMax error!");
         }but now receiving this error :
    BinarySearchTree.java: operator > cannot be applied to java.lang.Comparable,java.lang.Integer
             if(t.elementAt(t) > A && t.elementAt(t) < B) { //LINE 274 WITH ERROR
                                  ^
    BinarySearchTree.java: operator < cannot be applied to java.lang.Comparable,java.lang.Integer
             if(t.elementAt(t) > A && t.elementAt(t) < B) { //LINE 274 WITH ERROR
                                                        ^
    BinarySearchTree.java: cannot find symbol
    symbol  : method compareTo(java.lang.Integer)
    location: class BinaryNode<java.lang.Integer>
            if(t.findMin().compareTo(t.elementAt(t.root)) != 2 || t.findMax().compareTo(t.elementAt(t.root)) != NUMS - 2) {
                        ^
    BinarySearchTree.java: cannot find symbol
    symbol  : method compareTo(java.lang.Integer)
    location: class BinaryNode<java.lang.Integer>
            if(t.findMin().compareTo(t.elementAt(t.root)) != 2 || t.findMax().compareTo(t.elementAt(t.root)) != NUMS - 2) {The method compareTo takes an object as defined in the comparable interface which my BinarySearchTree extends. Binary Node is a child of BinarySearchTree. I've been messing around with where i initiate the compareTo method but not had any success, any idea/push in the right direction would be appreciated.
    Thanks

  • Binary Search Help

    Below is the coding for the binary search:
    public class Binary_Search_
    public int binarySearch(int arr[],int key)
    int low=0;
    int high=arr.length-1;
    while(low<=high)
    int middle=(low+high)/2;
    if(key==arr[middle])
    return middle;
    else
    if(key<arr[middle]) high=middle-1;
    else low=middle+1;
    return -1;//not found
    The only thing is that for the binary search the array must be sorted so what could I add to the start of the coding to quickly sort the array.
    You must think this is a simple question but im new to java!

    Another thing..
    Try rethinking your algorithm through.
    int middle=(low+high)/2will not always hit the center/middle/sweet spot (or what you would call it) of your array.
    If low was 2 and high was 5, your middle would be 3 (yes, 3), and if you are unlucky to have an array like this
    1, 2, 3, 5, 7, 11, 13, 17, 19your code would return -1 if you were searching for 5.
    And that's just one of a jillion possibilities.

Maybe you are looking for

  • Combining files in single pdf file

    After installing adobe acrobat 9 pro, I tried to opened the merged pdf file I had created in adobe 8 standard. I can see the combined folder in the "combine files" window, but I cannot open that file and expose the individual pdf files for sorting, r

  • Is PAP2's ok to connect to PBX instead of a standalone phone?

    Hello, We've tried to use another vendor's VoIP adapter and connect to our Panasonic PBX's CO line port, and then I dial out using one of the extension phone. But then it has serious echo problem, the remote end can hear my voice as an echo. I read t

  • User Defined Type - Array bind Query very slow

    Hi. I have following Problem. I try to use Oracle Instant Client 11 and ODP.NET to pass Arrays in SELECT statements as Bind Parameters. I did it, but it runs very-very slow. Example: - Inittial Query: SELECT tbl1.field1, tbl1.field2, tbl2.field1, tbl

  • Dual Screens - can you do it on the Essential All in One?

    I have a standard Essential all in one.   I thought it would be handy to run dual screens for something I am working on but cannot see a way to do this on the machine.  Is it possible?  Thanks AMC 

  • Replacement for FM C14G_TEXT_FORMAT

    Hi, I need an FM which works similar to FM C14G_TEXT_FORMAT. This takes up an input line and then depending on the length 'n' we mention, it splits up the line into multiple sublines , each of length of 'n' characters. Also takes language as a parame