A Java program that searches a text file using three classes
A Java program that searches a text file using three classes - LinearSearch, BinarySearch, RecursiveBinarySearch
The three classes extend SearchAlgorithm
ex:
---------
---------
The driver and exception is already built, when an algorithm is called i need it to find the index and state the amount of comparisons it took, and then refresh for other words.
example method call in driver:
--------
example textfile:
ALPHA
BRAVO
CHARLIE
DELTA
ECHO
----------
Calling
should return \'ECHO found at index: 4, taking 5 comparisons\"
should return \'ECHO found at index: 4, taking...\" and so on.
returns...
i just need to know how to search and compare strings properly using these 3 search algorithms, if you can make the three classes using the analogy above that would be great(making the iterave comparisons of strings, and then binary + recursive binary) if not, a general example of the three with a sorted(alphabetical) text file being called and displaying the index and # of comparisons would be sufficient
Solution
Here is the code for LinearSearch.java:
public class LinearSearch extends SearchAlgorithm
 {
 public int search(String[] words, String wordToFind) throws ItemNotFoundException
 {
 for(int i = 0; i < words.length; i++)
 if(words[i].compareTo(wordToFind) == 0)
 return i;
 }
return -1;
 }
Here is the code for BinarySearch.java:
public class BinarySearch extends SearchAlgorithm
 {
 public int search(String[] words, String wordToFind) throws ItemNotFoundException
 {
 int low = 0, high = words.length - 1, mid;
 while(low <= high)
 {
 mid = (low + high) / 2;
 if(words[mid].compareTo(wordToFind) == 0)
 return mid;
 else if(words[mid].compareTo(wordToFind) > 0)
 high = mid - 1;
 else
 low = mid + 1;
 }
return -1;
 }
 }
And the code for RecursiveBinarySearch.java is:
public class RecursiveBinarySearch extends SearchAlgorithm
 {
 public int search(String[] words, String wordToFind) throws ItemNotFoundException
 {
 return recursiveSearch(words, wordToFind, 0, words.length-1);
 }
 public int recursiveSearch(String[] words, String wordToFind, int low, int high)
 {
 if(low > high)
 return -1;
 int mid = (low + high) / 2;
 if(words[mid].compareTo(wordToFind) == 0)
 return mid;
 else if(words[mid].compareTo(wordToFind) > 0)
 return recursiveSearch(words, wordToFind, low, mid-1);
 else
 return recursiveSearch(words, wordToFind, mid+1, high);
 }
 }


