I'm trying to program a binary search in java. The program should read a pre-sorted list of words in alphabetical order, and search that list for a word. The problem I'm having is that I need to be able to typecast an object to a string. Here is my code so far:
CODE
import java.util.*;
import java.io.*;
public class BinarySearch
{
// instance variables
private int first, middle, last;
private int[] list;
public static void main (String args[]) {
// insert code here...
BufferedReader in = new BufferedReader(new FileReader("words.txt"));
BinarySearch jim = new BinarySearch();
LinkedList Bob = new LinkedList();
String temp;
while ((temp = in.readLine())!=null){
Bob.addLast (temp);
}
System.out.println(jim.search(Bob, "nofx"));
}
/**
* The main search method.
*
* @param list - the list to be sorted
* @param searchTarget - the value to be searched for
*
* @return middle or 0 - the location of the requested element is returned
* if it exists in the list, otherwise 0 is returned
*/
public int search(LinkedList list, String searchTarget)
{
last = list.size() - 1;
first = 0;
// while there are still elements to search through
while (first <= last)
{
middle = (first + last) / 2;
// if current middle value is the search target
if ((list.get(middle)).equals(searchTarget))
{
return middle;
}
// if current middle value is less than the search target
else if ((list.get(middle)).compareTo(searchTarget) < 0)
{
first = middle + 1;
}
// if current middle value is larger than the search target
else
{
last = middle - 1;
}
}
// return 0 if search target not found
return 0;
}
}
The error the compiler gives me is:
cannot find symbol : method compareTo(java.lang.String)
and
operator < cannot be applied to java.lang.String,int
Thanks in advance for any help.