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

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

• 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
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
}  //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
^
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.

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

• Search in object array

I am working on a program in which one of the problems is to search an object array to allow a user to edit an item in the array. I have examples on how to do linear and binary searches, but they are all simple strings of numeric data. How do I apply this algorithm to a more complex array?I have a class file called Application that contains my constructor, and my get & set methods for creating the objects in the array. And I have a driver class to allow a user to view the array, add items to it , and edit items in it.
This is an example of my declaration of the initial items:
Application inventory[] = new Application[100];
inventory[0] = new Application("Jumpstart Toddlers", 14.99, 500);
inventory[1] = new Application("Norton Antivirus 2003", 49.99, 1200);
etc....
I would like to set it up so that the user is prompted for the name of the software item they would like to edit, the array is searched using a method which returns the index the name was found in.

Sounds like a homework assignment to me but...
Appliction apps[] = new Application[100];
...Add Items to the apps array...
String software_to_search_for = .. user entered
data....
for (int i = 0; i < apps.length; ++i)
if
f
(apps.getSoftware().equalsIgnoreCase(software_to_sea
ch_for))
edit(apps[i], software_to_search_for);
public void edit(Application app, String newName)
// You can do anything here
app.setName(newName);
} // edit
True enough, this is an assignment. But..These assignments were given to us without all the necessary tools. They are set up by the dept. and we have to finish them even if the instructor does not finish covering all the relevant material.In this case, we have not covered the equalsIgnoreCase(something obviously necessary for my problem). Now that I know what I am looking for, I have found it in my book and can apply it to my code appropriately. I was not necessarily looking for code, just the tools I need for my own design. This is something that the Computer dept. allows for in that they have assistants in the open labs that will help in this manner. Problem is, everyone has been out for Thanksgiving since Tues. Please dont feel as though you assisted someone in cheating!! I can assure you, that is not the case here. Thank you for your help.

• Difference between Linear & Binary search.

Hi,
Could Anybody describe me, What is the difference between Linear Search and Binary Search in ABAP ?
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

• Java Linear, Quicksort, Binary Time Calc Problems

Objective of program: Simple program demonstrating the time it takes to do each algorithm.
My approach:
1) Prompt a number
2) Make array of linear ints
3) Calculate time it takes for a linear search
4) Repeat for quick sort, and Binary search
Problems:
1) Linear search time is always 0
2) Quick sort never ends.
3) Don't know if binary works yet since it never goes beyond quicksort.
Any help or suggestions are greatly appreciated.
import java.util.Date;
import java.util.ArrayList;
import java.util.Random;
import java.util.Arrays;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
Random generator = new Random();
int[] linear = new int[1000000];                           // Create Linear Array
for(int i = 0; i < linear.length; i++)                 // filling up the array
linear[i] = i;
Scanner input = new Scanner(System.in);
int search = input.nextInt();                              // Stores number
Date end = new Date();                                   // Create Timer
long startTime1 = end.getTime();                           // Start Time
for(int i = 0; i < linear.length; i++) {               // Linear Search
if (linear[i] == search) {
long endTime1 = end.getTime();                 // If found, end time
System.out.println("Time of Linear search: " + (endTime1 - startTime1));          // Prints elapsed time
break;
int[] quicksort = new int[1000000];                    // Creates quicksort array
for(int i = 0; i < quicksort.length; i++)                // Initializes the array
quicksort[i] = generator.nextInt(100000);
long startTime2 = end.getTime();                         // Starts the time
for(int i = 0; i < 1000000; i++)                         // Sorts...
Arrays.sort(quicksort);
long endTime2 = end.getTime();                         // Ends time
System.out.println("Time of QuickSort: " + (startTime2 - endTime2));               // Prints elapsed time
int[] binary = new int[1000000];                         // Creates binary array
for(int i = 0; i < binary.length; i++)                    // Initializes binary array
binary[i] = generator.nextInt();
long startTime3 = end.getTime();                         // Start time
Arrays.binarySearch(binary,search);                      // Binary Search
long endTime3 = end.getTime();                         // Ends time
System.out.println("Time of Binary Search: " + (endTime3 - startTime3));     // Prints out time
}Edited by: onguy3n on Mar 26, 2009 4:39 AM

ibanezplayer85 wrote:
Any help or suggestions are greatly appreciated.
Suggestion: Break your code up into different methods and even separate classes, if necessary; don't just use main for everything. Maybe you posted it this way to have it all in one class for the forum to read, but it's very confusing to look at it and understand it this way. I know that this isn't an answer to your question, but you did ask for suggestions :)Thanks, it was just a demonstration program in class so he didn't really care about readability, but yes I should have separated it in a different class.
>
Linear search time is always 0I'm not sure what the convention is, but whenever I needed to measure time for an algorithm, I used System.currentTimeMillis(); rather than the Date class.
e.g.
long startTime = System.currentTimeMillis();
long endTime = System.currenTimeMillis();
long totalTime = endTime - startTime;Although, I think if you're not printing anything out to the console, it will most likely print out 0 as the time (because most of the processing is working on printing out the data). That is, unless you're doing some heavy processing.Thanks! I tried System.currentTimeMillis() and it now works. I still don't understand your explanation why it prints out 0 though :(
>
Quick sort never ends.I think it's just taking a while. It's not an efficient algorithm with a worst case time complexity of O(n^2) and you gave it a very large array of random values to work with. I wouldn't be surprised if you ran out of heap space before it finished. If you knock off some zero's on the array size, you'll see that it does, in fact, finish.Ok, thanks! In class we didn't talk much about the heap. How do I calculate how much heap space my program will use and how to allocate more? I vaguely remember something like xmx512m or something as the parameter, but every time I get an error:
Unrecognized option: -xmx512m
Could not create the Java virtual machine.

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

• 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 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();
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; }
// And add it to the studentList
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
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()
import java.util.*;
private static Scanner keyboard = new Scanner(System.in);
int option;
option=0;
void display(){
// Clear the screen
System.out.println("\n1 Display");
System.out.println("\n2 Insert");
System.out.println("3 Quit");
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());
int chosenOption;
do{
for (Appointment app : appArray)
switch(chosenOption){
case 1 : app.display(); break;
default:;
}while(chosenOption != 3);
} // end main()
} // end class ObjectSortApp

• 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 sorting in Java

My program is suppose to search news articles and alphabetize all the words article individually of the text file. Right now the program alphabetizes all the words of the articles including the numbers. The text file will be located below the code. So basically i need to know how to alphabetize every articles words individually.
//This program reads an input line from the reader put the worda into an array with a count and increases
//the count each time a word is repeated. It then sorts the words alphabetically in the array and
//then prints out the array. There are 4 different articles like this one in the text file
<ID>58</ID>
<BODY>Assets of money market mutual funds
increased 720.4 mln dlrs in the week ended yesterday to 236.90
billion dlrs, the Investment Company Institute said.
Assets of 91 institutional funds rose 356 mln dlrs to 66.19
billion dlrs, 198 general purpose funds rose 212.5 mln dlrs to
62.94 billion dlrs and 92 broker-dealer funds rose 151.9 mln
dlrs to 107.77 billion dlrs.
</BODY>
import java.util.StringTokenizer;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.io.IOException;
import java.io.FileNotFoundException;
public class WordsFrequency
public static void main(String[] args)
// Initializations
FileWriter writer = null;
// Open input and output files
try
writer = new FileWriter("WordsReport.txt");
catch(FileNotFoundException e)
System.err.println("Cannot find input file");
System.exit(1);
catch(IOException e)
System.err.println("Cannot open input/output file");
System.exit(2);
// Set up to read a line and write a line
PrintWriter out = new PrintWriter(writer);
out.println("Copied file is: Words followed by frequency");
int count = 0;
wordCount[] wordsArray = new wordCount[100000];
boolean done = false;
while(!done)
String inputLine;
try
catch(IOException e)
System.err.println("Problem reading input, program terminates. " );
inputLine = null;
if (inputLine == null)
done = true;
sortbyWords(wordsArray,count);
for(int i = 0; i < count;i++)
out.println(wordsArray.toString());
else
StringTokenizer tokenizer = new StringTokenizer(inputLine);
while(tokenizer.hasMoreTokens())
String token = tokenizer.nextToken();
int lengthofString = token.length();
char ch = token.charAt(lengthofString-1);
if(ch == '.' || ch == ',' || ch == '!' || ch == '?' || ch == ';')
token = token.substring(0,lengthofString-1);
wordCount wordAndCount= new wordCount(token);
boolean skip = false;
for(int i = 0; i < count; i++)
if(token.equalsIgnoreCase(wordsArray[i].getWord()))
skip = true;
wordsArray[i].increaseFrequency();
if(skip == false)
wordsArray[count] = wordAndCount;
count++;
// Close files
try
in.close();
catch(IOException e)
System.err.println("Error closing file.");
finally
out.close();
public static void sortbyWords(wordCount [] wArray, int size)
wordCount temp;
for (int j = 0; j < size-1; j++)
for (int i = 0; i < size-1; i++)
if (wArray[i].getWord().compareToIgnoreCase(wArray[i+1].getWord()) > 0)
temp = wArray[i];
wArray[i] = wArray[i + 1];
wArray[i+1] = temp;
Edited by: IronManNY on Sep 25, 2008 3:24 PM

IronManNY wrote:
My program is suppose to search news articles and alphabetize all the words article individually of the text file. Right now the program alphabetizes all the words of the articles including the numbers. The text file will be located below the code. So basically i need to know how to alphabetize every articles words individually.You want to strip out the numbers?

• Search given string array and replace with another string array using Regex

Hi All,
I want to search the given string array and replace with another string array using regex in java
for example,
String news = "If you wish to search for any of these characters, they must be preceded by the character to be interpreted"
String fromValue[] = {"you", "search", "for", "any"}
String toValue[] = {"me", "dont search", "never", "trip"}
so the string "you" needs to be converted to "me" i.e you --> me. Similarly
you --> me
search --> don't search
for --> never
any --> trip
I want a SINGLE Regular Expression with search and replaces and returns a SINGLE String after replacing all.
I don't like to iterate one by one and applying regex for each from and to value. Instead i want to iterate the array and form a SINGLE Regulare expression and use to replace the contents of the Entire String.
One Single regular expression which matches the pattern and solve the issue.
the output should be as:
If me wish to don't search never trip etc...,
Kathir

As stated, no, it can't be done. But that doesn't mean you have to make a separate pass over the input for each word you want to replace. You can employ a regex that matches any word, then use the lower-level Matcher methods to replace the word or not depending on what was matched. Here's an example: import java.util.*;
import java.util.regex.*;
public class Test
static final List<String> oldWords =
Arrays.asList("you", "search", "for", "any");
static final List<String> newWords =
Arrays.asList("me", "dont search", "never", "trip");
public static void main(String[] args) throws Exception
String str = "If you wish to search for any of these characters, "
+ "they must be preceded by the character to be interpreted";
System.out.println(doReplace(str));
public static String doReplace(String str)
Pattern p = Pattern.compile("\\b\\w+\\b");
Matcher m = p.matcher(str);
StringBuffer sb = new StringBuffer();
while (m.find())
int pos = oldWords.indexOf(m.group());
if (pos > -1)
m.appendReplacement(sb, "");
sb.append(newWords.get(pos));
m.appendTail(sb);
return sb.toString();
} This is just a demonstration of the technique; a real-world solution would require a more complicated regex, and I would probably use a Map instead of the two Lists (or arrays).

• Search for Emails and place them on a array

I have the following asp/vbscript code that search for the
content of a folder with text files. I need someone to help me out
to modify the code to automatically search for email addresses on
each text file and place them on an array.

Bookmarks are stored in the bookmarks file.
These can't get your data back, but will help in the future.
These add-ons can be a great help by backing up and restoring Firefox
FEBE allows you to quickly and easily backup your
Firefox extensions, history, passwords, and more.
In fact, it goes beyond just backing up -- It will actually rebuild
your saved files individually into installable .xpi files.
It will also make backup of files that you choose.
Import/Export extension preferences

• 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);
} // end main
//================================================
//================================================
int option;
System.out.println("=============================================");
System.out.println(" ");
System.out.println("1. Find record (Advanced Search) ");
System.out.println("2. Quick Search ");
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 ");
// every menu option has its own method
if (option == 1)
FindRecord(records);
if (option == 2)
QuickSearch(records);
else if (option == 3)
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!");
//=================================================
// 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 1 is search based on first name
if (option == 1)
System.out.println("Enter First Name");
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");
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
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");
// 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");
} // 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;
//=================================================
//=================================================
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");
System.out.println("Enter the Last Name");
System.out.println("Enter the phone number");
// 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");
if (option == 2)
// 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;
while (option != 2);
//=================================================
// 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("----------------------------------");
//===============================================
// 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;
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)
return -1;
else if(result > 0)
return 1;
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

• Repeating Header and Footer on each page in Sub-Report

Post Author: Jimbob CA Forum: General I am formatting a report that has subreports.  I can get the header on every page, but the footer only appears on the last page.  How do I get a header and footer to print on each page of the subreport? Thanks fo

• Very subtle DB corruption ?

Hello all,     I'm experiencing what I call a very subtle bug. Subtle because there are no exceptions, no memory leak, not even an error message.     My application uses BDB XML and it inserts, updates, removes and searches documents - pretty basic f

• Problems and solutions for 9i DB R2 install on Redhat Linux AS 2.1

Installing 9iDB R2 9.2.0.1.0 on Redhat Linux Advanced Server 2.1 (aka Redhat Enterprise Linux (AS)) and applying patchset 2 (9.2.0.3.0) This is a certified platform but I hit many problems getting the install to work. Here are the problems I hit and

• Cost distribution SRM to R/3  - based on VALUE

Hi all, We are working on SRM 5.0 and R/3 4.7.,ECS In shopping cart when the cost dsitirbution is sleected as "VALUE",when the corresponding SRM PO replicates to R/3,the cost distribution always changes to percentage/quantity....Why is that R/3 syste

• ORA-00936: Missing Expression when using a claculation as a condition item

Hi I created a calculation below to create a subtotal on each row of a group of selected items. SUM(Invoice Amount)OVER(PARTITION BY Supplier Num ORDER BY Payment Currency Code) This worked fine - but then I wanted to create a condition based on this