Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The file attached contains all 50 state prefixes in a text file. The states are

ID: 3804843 • Letter: T

Question

The file attached contains all 50 state prefixes in a text file. The states are list in no particular order. You are to write a method that will open the text file (you should have appropriate exception handling), read the data into an array and then sort the data appropriately. States.txt

write a method that will appropriately search the sorted array of state abbreviations. The method will have as it's arguments, the array holding the states and the search value. The method should use a recursive binary search algorithm to carry out the search.

Explanation / Answer

assuming 50 states record are there in the text file. If you want to change number of records in text file please change array size accordingly.
otherwise program will failed due to null values. file handling exceptions taken care.
change the path of the file in program accordingly.
for any doubt or explanation please do comment.
program will return the position at which record is present in the array if you want to diaplay that record also simply add arr[n] in print statement.

import java.util.*;
import java.io.*;

class HelloWorld
{

public static void main(String args[]) throws FileNotFoundException
  
{
// System.out.pr
File text = new File("E:/States.txt");
  
//Creating Scanner instnace to read File in Java
String state_arr[]=new String[50];
Scanner scnr = new Scanner(text);
  
//Reading each line of file using Scanner class
int lineNumber = 0;
while(scnr.hasNextLine()){
String line = scnr.nextLine();
state_arr[lineNumber]=line;
lineNumber++;
}
Arrays.sort(state_arr);
  
/* Loop to display the sorted array...commented out.
for (String state_arr1 : state_arr) {
System.out.print(state_arr1);
System.out.println();
}
*/ String search = "indiana";
search(state_arr,search);
}

static void search (String arr[],String s)
{
int n = binarySearch(arr,0,(arr.length-1),s);
System.out.println("search token found at position: "+(n+1));
}
static int binarySearch(String arr[], int l, int r, String x)
{
if (r >= l)
{
int mid = l + (r - l)/2;

// If the element is present at the middle itself
if (arr[mid].equalsIgnoreCase(x)) return mid;

// If element is smaller than mid, then it can only be present
// in left subarray
int compare = arr[mid].compareToIgnoreCase(x);
if (compare>0) return binarySearch(arr, l, mid-1, x);

// Else the element can only be present in right subarray
return binarySearch(arr, mid+1, r, x);
}

// We reach here when element is not present in array
return -1;
}
}


Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote