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.
Similar Messages
-
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] = wWhat 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 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 libmainsysI 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. -
Dynamic java applet for binary search tree
dynamic java applet for deleting an element of a tree at any specified locationin the tree.
sorry, having thought a bit more about it let me try to be more correct and concrete. say i have feature a at arbitrary chromosome position 7 and features b at positions 1, 2, 3, 5, 6, 9, 10. right now i have to get the closest distance (Math.abs(7-6)) by doing brute force comparison of all values (Math.abs(7-1), Math.abs(7-2), so on). what i want to do is set up a binary tree thus (please forgive poor ASCII):
5
2 9
1 3 6 10
and get back the keys that the tree tried (since i know that 7 is not in the tree and a traditional binary search e.g. TreeMap.get(new Integer(7)) will return a null). i should get back 5, 9, 6, in an array/ArrayList and be able to find the closest feature b in three comparisons rather than 7. that doesn't seem like much but when you have a million b features the difference between 1000000 comparisons and log2(1000000) is pretty appreciable. so i am wondering if there is an extant class that will give me back the trace of attempted keys through a binary tree as described or, if not, if this would be horribly difficult to implement as an extension of TreeMap. -
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 -
How to use a standard library binary search if I'm not searching for a key?
Hi all,
I'm looking for the tidiest way to code something with maximum use of the standard libraries. I have a sorted set of ints that represent quality levels (let's call the set qualSet ). I want to find the maximum quality level (choosing only from those within qualSet ) for a limited budget. I have a method isAffordable(int) that returns boolean. So one way to find the highest affordable quality is to start at the lowest quality level, iterate through qualSet (it is sorted), and wait until the first time that isAffordable returns false. eg.
int i=-1;
for (int qual : qualSet) {
if !(isAffordable(qual))
return i;
i++;
}However isAffordable is a slightly complicated fn, so I'd like to use a binary search to make the process more efficient. I don't want to write the code for a binary search as that is something that should be reused, ideally from the standard libraries. So my question is what's the best way of reusing standard library code in this situation so as to not write my own binary search?
I have a solution, but I don't find it very elegant. Here are the important classes and objects.
//simple wrapper for an int representing quality level
class QualityElement implements Comparable<QualityElement>
//element to use to search for highest quality
class HiQualFinderEl extends QualityElement {
HiQualFinderEl(ComponentList cl) {...}
//class that contains fair amount of data and isAffordable method
class ComponentList {
boolean isAffordable(int qual) {...}
//sorted set of QualityElements
TreeSet<QualityElement> qualSet When you create an instance of HiQualFinderEl, you pass it a reference to a ComponentList (because it has the isAffordable() method). The HiQualFinderEl.compareTo() function returns 1 or -1 depending on whether the QualityElement being compared to is affordable or not. This approach means that the binary search returns an appropriate insertion point within the list (it will never act as if it found the key).
I don't like this because semantically the HiQualFinderEl is not really an element of the list, it's certainly not a QualityElement (but it inherits from it), and it just feels ugly! Any clever suggestions? Btw, I'm new to Java, old to C++.
If this is unclear pls ask,
AndyThanks Peter for the reply
Peter__Lawrey wrote:
you are not looking for a standard binary searchI'm not using a binary search in the very common I'm searching for a particular key sense, which is the Collections.binarySearch sense. But binary searches are used in other situations as well. In this case I'm finding a local maximum of a function, I could also be solving f(x)=0... is there a nice generic way to handle other uses of binary search that anyone knows of?
I would just copy the code from Collections.binarySearch and modify itI have this thing about reusing; just can't bring myself to do that :)
It would be quicker and more efficient than trying to shoe horn a solution which expects a trinary result.Not sure I understand the last bit. Are you referring to my bastardised compareTo method with only two results? If so, I know, it is ugly! I don't see how it could be less efficient though???
Thanks,
Andy -
Binary search tree - writing to a file in alphabetic order words from tree
Hi
I have written a program that will read a list of words from a file, insert these into a binary search tree, write words from the tree to another file, so that the resulting list contains words in ascending order. My input file Alpha1.txt contains the following contents in the order and format given (one word per line):
Dawn
Dave
Mike
Beth
David
Gina
Pat
Cindy
Sue
My program is supposed to be producing an alphabetical list of these words in another file "final.txt".
Instead it gives me the following list:
Dave Beth David Gina Cindy Sue Pat Mike Dawn
This is obviously wrong, right? My correct list in "final.txt" should be
Beth Cindy Dave David Dawn Gina Mike Pat Sue
I am not sure what is wrong with my code which I reproduce below:
import java.io.*;
import java.util.*;
//read Java Developer's Almanac from exampledepot.com
//Read this: http://en.wikipedia.org/wiki/Tree_traversal
/**preorder(node)
print node.value
if node.left ? null then preorder(node.left)
if node.right ? null then preorder(node.right)
public class AlphabeticBinarySortTree
private static TreeNode root;
private static TreeNode runner;
static String[] alphaArray;
static int alphaCounter;
private static TreeNode alphaRunner;
//Inner class
private static class TreeNode
String word;
TreeNode left;
TreeNode right;
int count;
public TreeNode(String word)
this.word = word;
left = null;
right = null;
public void insertAll(TreeNode newNode)
if(newNode.word.compareTo(runner.word) < 1)
System.out.println("newNode.word = " + newNode.word);
if(runner.left == null)
runner.left = newNode;
runner = runner.left;
else
insertAll(newNode);
else if(newNode.word.compareTo(runner.word) > 1)
System.out.println("newNode.word = " + newNode.word);
if(runner.right == null)
runner.right = newNode;
runner = runner.right;
else
insertAll(newNode);
else
count++;
}// end method insertAll
// Recursively print words (with counts) in sorted order
public static void printInPreOrder(TreeNode root)
System.out.println(root.word + " ");
if(root.left != null)
printInPreOrder(root.left);
if(root.right != null)
printInPreOrder(root.right);
} //end method printInPreOrder()
//called from inside main
public static void arrangeInAscendingOrder(TreeNode root, PrintWriter pWriter)
if(root.left != null)
arrangeInAscendingOrder(root.left, pWriter);
System.out.println();
System.out.println();
System.out.println(root.word + " ");
pWriter.write(root.word + " ");
if(root.right != null)
arrangeInAscendingOrder(root.right, pWriter);
}//end inner class TreeNode
public AlphabeticBinarySortTree()
root = null;
//belong to the outer class
public static void main(String[] args)
System.out.println("This program reads text from a file that it will parse. ");
System.out.println("In doing so, it will eliminate duplicate strings and ");
System.out.println("pick up only unique strings.These strings will be in a ");
System.out.println("stored in alphabetical order in a binary Search tree before they are ");
System.out.println("written out to another text file in alphabetic order");
//open the file for reading
try
BufferedReader bReader = new BufferedReader(new FileReader("Alpha1.txt"));
String words;
int count;
//System.out.println("A test to inspect the contents of words: " + words);
//System.out.println("Words =" + words);
count = 0;
//why is there an endless loop when
//I use "while(str != null)
StringTokenizer st;
st = null;
//based on http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html
while ((words = bReader.readLine()) != null)
st = new StringTokenizer(words);
while(st.hasMoreTokens())
//shiffman.net/teaching/a2z/concordance
String token = st.nextToken();
System.out.println("Token = " +token);
AlphabeticBinarySortTree.initiateInsert(token);
//count the number of tokens in the string
count++;
}//end inner while
}//end outer while
System.out.println("Here are the contents of your tree:");
//System.out.println("before the call to print()");
print();
System.out.println("the no of words in the file is: " + count);
bReader.close();
}//end of try
catch(IOException exception)
exception.printStackTrace();
/**try
FileWriter fWriter = new FileWriter("final.txt");
BufferedWriter bWriter = new BufferedWriter(fWriter);
PrintWriter pWriter = new PrintWriter(bWriter);
catch(IOExcepion exception)
exception.printStackTrace();
} // end main here
//this method belongs to the outer class
static void initiateInsert(String word)
//TreeNode is also static by the way
TreeNode newNode = new TreeNode(word);
if(root == null)
root = newNode;
System.out.println("root.word = " + root.word);
runner = root;
else
runner.insertAll(newNode);
// Start the recursive traversing of the tree
//without the access specifier 'static'
//I would get the following error message
//AlphabeticBinarySortTree.java:119: non-static method print() cannot be referenced from a static context
public static void print()
//System.out.println("**********AM I INSIDE THE PRINT() METHOD? ********");
if (root != null)
//System.out.println("++++++++ AM I INSIDE THE IF BLOCK OF THE PRINT() METHOD? +++++++");
//System.out.println("Inside THE IF BLOCK OF print() BUT BEFORE THE CALL TO printInPreOrder(),root.word = " + root.word);
AlphabeticBinarySortTree.TreeNode.printInPreOrder(root);
//open the file for writing
try
FileWriter fWriter = new FileWriter("final.txt");
BufferedWriter bWriter = new BufferedWriter(fWriter);
PrintWriter pWriter = new PrintWriter(bWriter);
AlphabeticBinarySortTree.TreeNode.arrangeInAscendingOrder(root, pWriter);
pWriter.close();
catch(IOException eException)
eException.printStackTrace();
}//end of if block
} // end of method print
}//end outer enclosing class here--------
All help is highly appreciated. Thanks for your time and consideration.You suggest that I do away with the inner class
then?Absolutely. In fact I strongly suggest this. You are learning how to code and need to do things cleanly and in small steps. That means first creating your Node class and making sure it works. Then creating your Tree class, and making sure it works. In fact I would load the Strings into the Tree class first directly and testing things before even thinking about reading to and from files. Only then should you implement the file input and output steps.
The key here is that you don't go on to the next step until you're reasonably sure that your current code works. Remember, it's MUCH easier to code than to debug. -
Creating A Binary search algorithm !!!! URGENT HELP
hi ..
i;m currently tryin to create a binary search algorithm ..
the user should be able to input the size of the array
and also the key that he would like to find.
it also has to have to ability to measure the run time of the algorithm.. it how long it too the algorithm to search through the array and find they key..
i have created 3 classes
the first class is the binary search class
which is the mathamatical side of things
the second class is the Array
this creates an array selection a random first number
and then incrementing from there, so that its a sorted array
the third class is the binary search class
which is my main class.
this class should take the users input
and pass it to the array
and the binary seach accordingly
it should also measure the running time, from when it passes the array
to the binary search class
i am having a really hard time creating this last class.
i have created the other 2 successfully
the codes for the binary search class is as follows
public class BinarySearch
static int binSearch(int[] array, int val)
// setting the start and the end of the array
int low = 0, high = array.length;
//While loop
while(low <= high) {
// How to find the mid point
int mid = (low + high)/2;
// if the mid point is the value return the value
if(array[mid] == val) {
return mid;
// if the value is smaller than the mid point
// go search the left half
} else if(array[mid] > val) {
high = mid - 1;
//if the value is greater then the mid point
// go search the right half
} else if(array[mid] < val) {
low = mid + 1;
// if value is not found return nothing
return -1;
}and the code for the Array class is as follows
import java.util.Random;
public class RandomSortedArray
public int[] createArray(int length)
// construct array of given length
int[] ary = new int[length];
// create random number generator
Random r = new Random();
// current element of the array; used in the loop below. Starts at
// -1 so that the first element of the array CAN be a 0
int val = -1;
for( int i = 0; i < length; i++)
val += 1 + r.nextInt(10);
ary[i] = val;
return ary;
}can some pne please help me create my binarysearchTest class.
as i mentioned before
it has to take the users input for the array size
and the users input for the value that they want to find
also needs to measure the running time
thanks for all ur help in advanceimport 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 -
Problem with binary search tree
Hi all, just having troubles with a program im writing.
My program is based on a binary search tree full of items which are passed in via an input file and then saved to an output file.
I have written a sellItem method which gets passed in the item and quantity that has been sold which then needs to be changed in the binary tree.
Here if my sell Item method:
public void sellItem(Item item, int quantity){
stockItem = item;
mQuantity = quantity;
if (tree.includes(stockItem)){
int tempQuantity = stockItem.getQuantityInStock();
tempQuantity -= mQuantity;
else{
throw new IllegalArgumentException("The Barcode " + mBarCode + " does NOT exist.");
}and here is where i am calling it in a test class :
number1.sellItem(item1, 40);Each item is in this format :
ABCD, PENCIL, 1, 0.35, 200, 100, 200
where 200 is the quantity.
Therefore if i pass 40 into the method the binary search tree should then store the quantity as 160.
below is a copy of my binary tree :
public class BSTree extends Object {
private class TreeNode extends Object{
public Comparable data;
public TreeNode left;
public TreeNode right;
public TreeNode() {
this(null);
public TreeNode(Comparable barCode){
super();
data = barCode;
left = null;
right = null;
private TreeNode root;
private int nodeCount;
public BSTree(){
super();
root = null;
nodeCount = 0;
public boolean isEmpty() {
return root == null;
public int size() {
return nodeCount;
private TreeNode attach(TreeNode newPointer, TreeNode pointer){
if (pointer == null){
nodeCount++;
return newPointer;
else {
Comparable obj1 = (Comparable) newPointer.data;
Comparable obj2 = (Comparable) pointer.data;
if (obj1.compareTo(obj2) < 0) //Go left
pointer.left = attach(newPointer, pointer.left);
else //Go right
pointer.right = attach(newPointer, pointer.right);
return pointer;
public void insert(Comparable item){
//Create a new node and initialize
TreeNode newPointer = new TreeNode(item);
//Attach it to the tree
root = attach(newPointer, root);
public Comparable remove(Comparable key) {
TreeNode pointer;
TreeNode parent;
//Find the node to be removed
parent = null;
pointer = root;
while ((pointer != null) && !key.equals(pointer.data)) {
parent = pointer;
if (key.compareTo(pointer.data) <0)
pointer = pointer.left;
else
pointer = pointer.right;
if (pointer == null)
return null;
//Orphans
TreeNode leftSubtree = pointer.left;
TreeNode rightSubtree = pointer.right;
if (parent == null)
root = null;
else if (key.compareTo(parent.data) < 0)
parent.left = null;
else
parent.right = null;
//Reattaching any orphans in the left subtree
if (leftSubtree != null) {
root = attach(leftSubtree, root);
nodeCount--;
//Reattaching any orphans in the right subtree
if (rightSubtree != null) {
root = attach(rightSubtree, root);
nodeCount--;
nodeCount--;
return pointer.data;
private TreeNode search(TreeNode pointer, Comparable key) {
if (pointer == null)
return null;
else if (pointer.data.compareTo(key) == 0)
return pointer;
else if (key.compareTo(pointer.data) < 0)
return search(pointer.left, key);
else
return search(pointer.right, key);
public boolean includes(Comparable key) {
return (search(root, key) != null);
public Comparable retrieve(Comparable key) {
TreeNode pointer;
pointer = search(root, key);
if (pointer == null)
return null;
else
return pointer.data;
public Comparable[] getAllInOrder() {
Comparable[] list = new Comparable[nodeCount];
inOrderVisit(root,list,0);
return list;
private int inOrderVisit(TreeNode pointer, Comparable[] list, int count) {
if (pointer != null) {
count = inOrderVisit(pointer.left, list, count);
list[count++] = pointer.data;
count = inOrderVisit(pointer.right, list, count);
return count;
public String toString() {
StringBuffer result = new StringBuffer(100);
inOrderString(root, result);
return result.toString();
private void inOrderString(TreeNode pointer, StringBuffer result) {
if (pointer != null) {
inOrderString(pointer.left, result);
result.append(pointer.data.toString() + "\n");
inOrderString(pointer.right, result);
}Thanks for everyones help. Keep in mind i'm very new to java.Hi all, just having troubles with a program im writing.
My program is based on a binary search tree full of items which are passed in via an input file and then saved to an output file.
I have written a sellItem method which gets passed in the item and quantity that has been sold which then needs to be changed in the binary tree.
Here if my sell Item method:
public void sellItem(Item item, int quantity){
stockItem = item;
mQuantity = quantity;
if (tree.includes(stockItem)){
int tempQuantity = stockItem.getQuantityInStock();
tempQuantity -= mQuantity;
else{
throw new IllegalArgumentException("The Barcode " + mBarCode + " does NOT exist.");
}and here is where i am calling it in a test class :
number1.sellItem(item1, 40);Each item is in this format :
ABCD, PENCIL, 1, 0.35, 200, 100, 200
where 200 is the quantity.
Therefore if i pass 40 into the method the binary search tree should then store the quantity as 160.
below is a copy of my binary tree :
public class BSTree extends Object {
private class TreeNode extends Object{
public Comparable data;
public TreeNode left;
public TreeNode right;
public TreeNode() {
this(null);
public TreeNode(Comparable barCode){
super();
data = barCode;
left = null;
right = null;
private TreeNode root;
private int nodeCount;
public BSTree(){
super();
root = null;
nodeCount = 0;
public boolean isEmpty() {
return root == null;
public int size() {
return nodeCount;
private TreeNode attach(TreeNode newPointer, TreeNode pointer){
if (pointer == null){
nodeCount++;
return newPointer;
else {
Comparable obj1 = (Comparable) newPointer.data;
Comparable obj2 = (Comparable) pointer.data;
if (obj1.compareTo(obj2) < 0) //Go left
pointer.left = attach(newPointer, pointer.left);
else //Go right
pointer.right = attach(newPointer, pointer.right);
return pointer;
public void insert(Comparable item){
//Create a new node and initialize
TreeNode newPointer = new TreeNode(item);
//Attach it to the tree
root = attach(newPointer, root);
public Comparable remove(Comparable key) {
TreeNode pointer;
TreeNode parent;
//Find the node to be removed
parent = null;
pointer = root;
while ((pointer != null) && !key.equals(pointer.data)) {
parent = pointer;
if (key.compareTo(pointer.data) <0)
pointer = pointer.left;
else
pointer = pointer.right;
if (pointer == null)
return null;
//Orphans
TreeNode leftSubtree = pointer.left;
TreeNode rightSubtree = pointer.right;
if (parent == null)
root = null;
else if (key.compareTo(parent.data) < 0)
parent.left = null;
else
parent.right = null;
//Reattaching any orphans in the left subtree
if (leftSubtree != null) {
root = attach(leftSubtree, root);
nodeCount--;
//Reattaching any orphans in the right subtree
if (rightSubtree != null) {
root = attach(rightSubtree, root);
nodeCount--;
nodeCount--;
return pointer.data;
private TreeNode search(TreeNode pointer, Comparable key) {
if (pointer == null)
return null;
else if (pointer.data.compareTo(key) == 0)
return pointer;
else if (key.compareTo(pointer.data) < 0)
return search(pointer.left, key);
else
return search(pointer.right, key);
public boolean includes(Comparable key) {
return (search(root, key) != null);
public Comparable retrieve(Comparable key) {
TreeNode pointer;
pointer = search(root, key);
if (pointer == null)
return null;
else
return pointer.data;
public Comparable[] getAllInOrder() {
Comparable[] list = new Comparable[nodeCount];
inOrderVisit(root,list,0);
return list;
private int inOrderVisit(TreeNode pointer, Comparable[] list, int count) {
if (pointer != null) {
count = inOrderVisit(pointer.left, list, count);
list[count++] = pointer.data;
count = inOrderVisit(pointer.right, list, count);
return count;
public String toString() {
StringBuffer result = new StringBuffer(100);
inOrderString(root, result);
return result.toString();
private void inOrderString(TreeNode pointer, StringBuffer result) {
if (pointer != null) {
inOrderString(pointer.left, result);
result.append(pointer.data.toString() + "\n");
inOrderString(pointer.right, result);
}Thanks for everyones help. Keep in mind i'm very new to java. -
Is there a way of executa a binary search directlly over a file ? a java native way ?
That would work best with a RandomAccessFile, since a binary search jumps back and forth looking at different places in the search space. And it would have to be a RandomAccessFile with fixed record lengths, sorted in the correct sequence. There is no method in the standard API to do that, but you could write the binary search code without much difficulty.
-
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 methodIt 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 -
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!.
ThanksSo 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 -
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. -
[Help] Binary Search
I want to do a binary search on a sorted array list.
My question is,
In the java.util package, there is a pre-written methods, Arrays.binarySearch() which I can use it to do the searching straight forward. What I concern here, if I write the binary search algorithm myself, will it be fastest?
Let's assume, there are only integers in the array, and the binary search algorithm that I am going to write in traditional way that widely used today.Whenever there is a method available in the API we need not write the method once again. All the way whatever we write may contain some pit-falls and it may fail some where at the same it won't be that much efficient also.
-
How many different binary search trees can store the keys {1,2,3}
I am having a hard time answering this question:
How many different binary search trees can store the keys {1,2,3} or how about {1,2,3,4} and how did u figure this out?
Any responses helpful
Thanks!the.maltese.falcon wrote:
practissum, shame on you for doing this chap's homework for him. @ the OP, this is a Java forum, not a basic data structures forum.
Also, you forgot the cases
3
1
2and
1
3
2
the.maltese.falcon, I was just trying to help him get started with the base case. Notice that I didn't enumerate all of the possibilities, but was trying to help the OP get on the right track. You, however, have done this. So shame to you, sir!
Maybe you are looking for
-
Download Adobe LiveCycle Designer ES 9.0
I got below error message while click on Edit in Adobe Pro XI. After some research I found that the form was created using "Adobe LiveCycle Designer ES 9.0" application ( File-->Properties ). Now I started to download LiveCycle to modify this form bu
-
Unable to connect to itunes and youtube
Hi i have recently reseted my ipod using the reset button in the ipod coz i was unable to delete the unwanted pics and songs. Its very difficult in terms of deleting the items thats no longer required. After this, i am unable to go to itunes and yout
-
MacBook/Macbook Pro and Final Cut Studio
I am about to buy a Mac, but im not sure if I should get the MacBook or MacBook Pro? Which is better suited for Final Cut Studio? Is there a specific version of the MacBook/MacBook Pro that would be best? Thanks so much!
-
Sourcing Indicator incorrectly set
Hi All, I have a strange situation where the sourcing indicator is being set for all shopping cart items even though a Purchase Order has been created. It seems that when BBP_GET_STATUS_2 the sorucing indicator is being set regardless of any conditio
-
FG material in Prod Ord once 101, goes to Quality Inspection Stocks
Hello, I would like to ask, why does one of our Finished Goods in our production order once confirmation 101 was done to it, the stock went to the Quality Inspection Stocks? We have check its material master data Quality Management Tab and below are