I am writing a program that takes a file and writes it's contents to an array. Then the array is sorted with a selection sort algorithm and then can be searched using the binary search algorithm. The array can not have more than 100 elements and I can't use user-defined classes.
/*Griffen Fox
CS 110
Assignment 5
Question 1
*/
import java.util.Scanner;
import java.io.*;
public class WordsSearchProgram
{
public static void main(String[] args)throws IOException
{
//Loads Words.txt to an array
final int SIZE = 100; //Size of the array
String[] words = new String[SIZE]; // creates the array
int index = 0; // Loop Control Variable
//Opens the File
File file = new File("words.txt");
Scanner inputFile = new Scanner(file);
//Reads Contents Into Array
while (inputFile.hasNext() && index < words.length)
{
words[index] = inputFile.nextLine();
index++;
}
//Close File
inputFile.close();
int search;
for (index = 0; index < words.length; index++)
{
search = searchString(words, words[index]);
if (search >= 0)
{
System.out.println(words[index] + " is at index " + search);
}
else
{
System.out.println(words[index] + " is not in the array.");
}
}
}
//Selection Sort Algorithm
public static String[] sort(String[] words)
{
for (int i = words.length - 1; i >= 1; i--)
{
// Find the maximum in the list[0..i]
String currentMax = words[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++)
{
if (currentMax.compareTo(words[j]) < 0)
{
currentMax = words[j];
currentMaxIndex = j;
}
}
// Swap list[i] with list[currentMaxIndex] if necessary;
if (currentMaxIndex != i)
{
words[currentMaxIndex] = words[i];
words[i] = currentMax;
}
}
return words;
}
//Binary Search String
public static int searchString(String[] words, String key)
{
int first = 0;
int last = words.length;
int position = -1;
boolean found = false;
while (!found && first <= last)
{
int mid = ((first + last) / 2);
if (key.compareTo(words[mid]) == 0)
{
found = true;
position = mid;
}
else if (key.compareTo(words[mid]) > 0)
{
first = mid - 1;
}
else
{
first = mid + 1;
}
}
return position;
}
}