Write a program that loads the words in words.txt into an array of strings. Ther
ID: 3544091 • Letter: W
Question
Write a program that loads the words in words.txt into an array of strings. There is one word per line and an
unknown number of lines in the file. If there are more than 100, read only the first 100. Sort the strings using a
selection sort. Prompt the user for a string to search for. Use the binary search to locate the string and indicate
to the user whether the string exists in the list or not. Searching and sorting should be case-insensitive. No
user-defined classes are required.
Here is what is in words.txt:
charm
island
start
voice
yard
glass
sharp
square
part
candle
hard
granite
puppy
chart
speaker
under
crate
number
grass
sister
ride
winter
teeth
temper
ear
thunder
dance
any
bag
many
light
together
house
car
radio
leather
carpet
ring
pillow
wood
frame
chair
Explanation / Answer
package javaapplication4;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class JavaApplication4 {
public static String[] selectionSort(String[] s, int lineCount) {
for (int i = lineCount - 1; i >= 1; i--) {
// Find the maximum in the list[0..i]
String currentMax = s[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++) {
if (currentMax.compareTo(s[j]) < 0) {
currentMax = s[j];
currentMaxIndex = j;
}
}
// Swap list[i] with list[currentMaxIndex] if necessary;
if (currentMaxIndex != i) {
s[currentMaxIndex] = s[i];
s[i] = currentMax;
}
}
return s;
}
public static int binarySearch(String[] a, String key, int lineCount) {
int low = 0;
int high = lineCount - 1;
while (low <= high) {
int middle = (low + high) / 2;
if (key.compareTo(a[middle]) > 0) {
low = middle + 1;
} else if (key.compareTo(a[middle]) < 0) {
high = middle - 1;
} else { // The element has been found
return middle + 1;
}
}
return -1;
}
public static void main(String[] args) throws IOException {
FileInputStream file = new FileInputStream("words.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(file));
String line;
int lineCount = 0;
String[] arr = new String[100];
while ((line = br.readLine()) != null && lineCount < 100) {
arr[lineCount++] = line;
}
br.close();
arr = selectionSort(arr, lineCount);
System.out.println("Enter the word you want to search for: ");
Scanner terminalInput = new Scanner(System.in);
String input = terminalInput.nextLine();
int found = binarySearch(arr, input, lineCount);
if (found == -1) {
System.out.println(input + " not found in words.txt");
} else {
System.out.println(input + " found at position " + found);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.