***Is this code correct? I am trying to do sequential Search on an array of 20 s
ID: 3691815 • Letter: #
Question
***Is this code correct? I am trying to do sequential Search on an array of 20 strings. The variable comparisons is just to get the number of iterations (part of the assigment).
***How the recursive version of this looks like?
//Sequential Search method
public static boolean sequentialSearch(String[] a, String item){
int counter=0;
boolean found = false;
int pos= -1;
int comparisons = 0;
while(!found && counter<a.length){
comparisons++;
if (a[counter] == item){
found = true;
pos = counter;
counter++;
}
}
System.out.println(comparisons);
return found;
}
Explanation / Answer
Try this code
import java.util.Scanner;
import java.io.*;
public class Searching
{
static int comparisons = 0;
public static void main (String [] args)
{
String [] wordsA = new String [0], wordsB = new String [0];
try
{
wordsA = readFile ("A.txt");
wordsB = readFile ("B.txt");
}
catch (IOException WrongFormat)
{
System.out.println ("There was a problem reading one (or both) of the files.");
}
//OUTPUT
long before, time;
int position;
//SEQUENTIAL
System.out.println ("Sequential Search");
System.out.println ("Word Position Comparisons Time (ms)");
for (int i = 0; i < wordsA.length; i++)
{
before = System.currentTimeMillis ();
position = sequentialSearch (wordsA[i], wordsB);
time = System.currentTimeMillis () - before;
System.out.println (wordsA[i] + " " + position + " " + comparisons + " " + time);
}
}
public static String [] readFile (String fileName) throws IOException
{
Scanner s = new Scanner (new FileReader (fileName));
String [] file = new String [Integer.parseInt (s.nextLine ())];
for (int i = 0; i < file.length; i++)
{
file[i] = s.nextLine ();
}
s.close ();
return file;
}
public static int sequentialSearch (String word, String [] wordList)
{
comparisons = 0;
int position = 0;
for (int i = 0; i < wordList.length; i++)
{
comparisons++;
//System.out.println (word + ": " + wordList [i] + " i: " + i);
if (word.equalsIgnoreCase (wordList[i]))
{
return (i+1);
}
else if (word.compareTo (wordList[i]) < 0)
{
return -1;
}
}
return -1;
}
}
Hope this will help you
Thank you!
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.