The program takes an array of strings and a string key as input, and returns the index of the string in the array if it is found, or -1 if it is not.
The linear search algorithm iterates through each element of the array and checks if it is equal to the key. If it is, it returns the index of that element. If it is not, it continues until the end of the array is reached. If the end of the array is reached, the program returns -1, indicating that the key is not found.
To compare 2 strings s1 and s2, use the compareTo( ) method.
Use this test program to test your linearSearch( ) method:
public class myProg
{
public static void main(String[] args)
{
String[] list1 = {"john", "mary", "jason", "edward", "peter"};
System.out.println( linearSearch(list1, "jason") );
System.out.println( linearSearch(list1, "jacob") );
String[] list2 = {"x", "ab", "xa", "xy", "az", "dc", "ac"};
System.out.println( linearSearch(list2, "XY") );
System.out.println( linearSearch(list2, "xy") );
}
// Write your linearSearch() method here
}
|
The output of the test program should be:
2 -1 -1 3 |