In: Computer Science
Java String search
Design and implement a recursive version of a binary
search. Instead of using a loop to repeatedly check for
the target value, use calls to a recursive method to check one
value at a time. If the value is not the target, refine
the search space and call the method again. The name to
search for is entered by the user, as is the indexes that define
the range of viable candidates can be entered by the user (that are
passed to the method). The base case that ends recursion is either
finding the value within the range or running out of data to
search. The program will work on an array of sorted
String objects read in from a text file. Your program
will generate an exception, that provides a message to the user, if
the file can't be found or if the starting index is after the
ending index. You will create your own text file of
first names in alphabetical order (binary search required ordering)
to test your program, make sure to include that file with your
submission.
If you need any clarifications kindly comment
Program
import java.io.*;
public class Main
{
public static void main(String[] args)throws Exception
{
//File file = new
File("C:\\java\\input.txt");
//String file =
"c:/java/input.txt";
String[] arr={};
int i=0;
BufferedReader bufReader
= new BufferedReader(new FileReader("C:\\java\\input.txt"));
try
{
String line =
bufReader.readLine();
while (line !=
null)
{
arr[i]=line;
line = bufReader.readLine();
}
}
catch (IOException
e)
{
e.printStackTrace();
}
bufReader.close();
String x = "contribute"; //key
value
int n = arr.length;
int result = binarySearch(arr,
x,0,n-1);
if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index " + result);
}
// Returns index of x if it is present in a[], else
return -1
public static int binarySearch(String[] a, String
x,int l,int r)
{
if (l > r)
return -1;
int mid = l + (r - l) / 2;
if (a[mid].compareTo(x) <
0)
return binarySearch(a, x, mid + 1, r);
else if
(a[mid].compareTo(x) > 0)
return binarySearch(a, x, l, mid - 1);
else
return mid;
}
}
input.txt
hello
hai
practice
java
program