Question

In: Computer Science

JAVA CODE Learning objectives; File I/O practice, exceptions, binary search, recursion. Design and implement a recursive...

JAVA CODE

Learning objectives; File I/O practice, exceptions, binary search, recursion.

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.  

Just a reminder, don’t forget to submit all the required files and screenshots, including multiple runs showing both finding and not finding a name, an example of your exception being thrown and the message displayed for indices not within range, and the data file that you used. You should have used at least 30 first names to effectively demonstrate a binary search starting between indices.

Solutions

Expert Solution

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class RecursiveBinarySearch {

 Â

private static int recursiveBinarySearch(String arr[], int leftIndex, int rightIndex, String target)

{

int index = -1;

if(rightIndex >= leftIndex && leftIndex < arr.length - 1)

{

int midIndex = leftIndex + (rightIndex - leftIndex) / 2;

if(arr[midIndex].compareToIgnoreCase(target) == 0)

index = midIndex;

else if(arr[midIndex].compareToIgnoreCase(target) > 0)

index = recursiveBinarySearch(arr, leftIndex, midIndex - 1, target);

else

index = recursiveBinarySearch(arr, midIndex + 1, rightIndex, target);

}

return index;

}

 Â

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

Scanner fileReader;

System.out.print("Enter the input file name: ");

String inFileName = sc.nextLine().trim();

 Â

// read file to count number of names

int countStrs = 0;

try

{

fileReader = new Scanner(new File(inFileName));

while(fileReader.hasNextLine())

{

String s = fileReader.nextLine();

countStrs++;

}

fileReader.close();

}catch(FileNotFoundException fnfe){

System.out.println(inFileName + " could not be found! Exiting..");

System.exit(0);

}

 Â

// read all names from input file

System.out.println("\nAttempting to read " + inFileName + "..");

String names[] = new String[countStrs];

int index = 0;

try

{

fileReader = new Scanner(new File(inFileName));

while(fileReader.hasNextLine())

{

names[index++] = fileReader.nextLine().trim();

}

System.out.println(countStrs + " names successfully read from " + inFileName + ".");

fileReader.close();

}catch(FileNotFoundException fnfe){

System.out.println(inFileName + " could not be found! Exiting..");

System.exit(0);

}

 Â

// sort the array of names in ascending order

for(int i = 0; i < countStrs - 1; i++)

{

for(int j = 0; j < countStrs - i - 1; j++)

{

if(names[j].compareToIgnoreCase(names[j + 1]) > 0)

{

String temp = names[j];

names[j] = names[j + 1];

names[j + 1] = temp;

}

}

}

 Â

// prompt user to enter the name to search

System.out.println();

String target;

do

{

System.out.print("Enter the target name (quit to stop): ");

target = sc.nextLine().trim();

if(target.equalsIgnoreCase("quit"))

break;

int resultIndex = recursiveBinarySearch(names, 0, countStrs - 1, target);

if(resultIndex == -1)

System.out.println("Sorry! " + target + " is not found in the array.\n");

else

System.out.println(target + " is found at index " + (resultIndex + 1) + ".\n");

}while(!target.equalsIgnoreCase("quit"));

 Â

}

}

INPUT FILE (names.txt) - This file needs to be created before running the code and this file should be created within the same working project directory where the above RecursiveBinarySearch.java file will be residing.


Related Solutions

Java String search Design and implement a recursive version of a binary search.  Instead of using a...
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...
Iterative Linear Search, Recursive Binary Search, and Recursive Selection Sort I need it in Java with...
Iterative Linear Search, Recursive Binary Search, and Recursive Selection Sort I need it in Java with comments and I need the input file to be placed with Scanner not BufferedReader Please help I need Class River Class CTRiver and Class Driver Class River describes river’s name and its length in miles. It provides accessor methods (getters) for both variables, toString() method that returns String representation of the river, and method isLong() that returns true if river is above 30 miles...
This assignment will give you practice in Handling Exceptions and using File I/O. Language for this...
This assignment will give you practice in Handling Exceptions and using File I/O. Language for this program is JAVA Part One A hotel salesperson enters sales in a text file. Each line contains the following, separated by semicolons: The name of the client, the service sold (such as Dinner, Conference, Lodging, and so on), the amount of the sale, and the date of that event. Prompt the user for data to write the file. Part Two Write a program that...
PLESE CODE IN C# not java RECURSION Objectives • Learn the basics of recursion – Part...
PLESE CODE IN C# not java RECURSION Objectives • Learn the basics of recursion – Part II (last week was Part I) Submission Guidelines: You will turn in 2 program files (one for each lab problem) Tasks This lab has two parts: Write a driver program that calls this method from the Main program. • • Write a driver program that calls this method from the Main program. Note: Your program name should match the name of your java /...
Implement a recursive binary search on an array of 8-byte integers in LEGV8
Implement a recursive binary search on an array of 8-byte integers in LEGV8
Write a recursive method to implement Binary Search of a sorted integer array. Signature of method...
Write a recursive method to implement Binary Search of a sorted integer array. Signature of method could be public int BinarySearch(int target, int low, int high)
Write a recursive method to implement Binary Search of a sorted integer array. Signature of method...
Write a recursive method to implement Binary Search of a sorted integer array. Signature of method could be public int BinarySearch(int target, int low, int high)
I am trying to implement a search function for a binary search tree. I am trying...
I am trying to implement a search function for a binary search tree. I am trying to get the output to print each element preceding the the target of the search. For example, in the code when I search for 19, the output should be "5-8-9-18-20-19" Please only modify the search function and also please walk me through what I did wrong. I am trying to figure this out. Here is my code: #include<iostream> using namespace std; class node {...
a java code In this lab you will implement an inorder traversal, and a search for...
a java code In this lab you will implement an inorder traversal, and a search for a 2-3-4 tree. The inorder traversal will print the contents (integers) of the tree, and the search method will return a boolean, indicating whether a given key was found in the tree. Examine the provided template. The main method is provided for you, as well as a template of the Node and 2-3-4 classes. The main method will read either "inorder" or an integer...
Language: Java Design and implement a program that implements an Interpolation Search method. Interpolation search is...
Language: Java Design and implement a program that implements an Interpolation Search method. Interpolation search is similar to binary search, except it tries to begin the search nearer to the location of the item. Instead of the using the middle value of the sorted array, interpolation search estimates the location of the target with respect to the first & last values in the array. The implementation is the same as binary search except that you should calculate the mid value...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT