I wrote a program for a Java class that I am taking to search a String array for a specific target. The program searches for the target from the beginning of the array to the end of the array and then searches from the end of the array to the beginning of the array. I am supposed to test the speed of both searches to see which one is faster. How can I test this?
Here is the program:
public class LinearStringSearch {
// Array filled with random Strings
String[] randomStrings = {"apple", "yellow", "fire", "wood", "zinc",
"ram", "mouse", "fish", "cheese", "dirt"};
// Save target arguments for global access(console printing purposes)
String target;
String target2;
/**
*
* @param target - the item you want to retrieve from array
* @param sa - the name of the array
* @return i - the target, otherwise return error code: -1
*/
int linearStringSearch(String target, String[] sa) {
this.target = target; // set class variable for print access
for(int i = 0; i < sa.length; ++i) {
System.out.println("Searching array position: " + i);
if (sa[i].equals(target)) {
// System.out.println("Target found! ");
return i;
}
}
return -1;
}
/**
*
* @param target - the item you want to retrieve from array
* @param sa - the name of the array
* @return i - the target, otherwise return error code: -1
*/
int backwardLinearStringSearch(String target, String[] sa) {
this.target2 = target; // set class variable for print access
for(int i = 9; i < sa.length; --i) {
System.out.println("Searching array position: " + i);
if (sa[i].equals(target)) {
return i;
}
}
return -1; // -1 means that target was not found
}
/*
* The target string is searched from the beginning of the array to the end of the array, then
* from the end of the array to the beginning of the array.
*/
public static void main(String[] args) {
LinearStringSearch lss = new LinearStringSearch();
// Search array from beginning to end
System.out.println("Linear search: "); // Print title
int index = lss.linearStringSearch("mouse", lss.randomStrings); // Pass arguments
System.out.println("The target " + "'" + lss.target + "'" + // Print to console
" found at array index: "+index);
// Search array from end to beginning
System.out.println("\nBackwards linear search: "); // Print title
int index2 = lss.backwardLinearStringSearch("mouse", lss.randomStrings); // Pass arguments
System.out.println("The target " + "'" + lss.target2 + "'" + // Print to console
" found at array index: "+index2);
}
}
Here is the output:
Linear search:
Searching array position: 0
Searching array position: 1
Searching array position: 2
Searching array position: 3
Searching array position: 4
Searching array position: 5
Searching array position: 6
The target 'mouse' found at array index: 6
Backwards linear search:
Searching array position: 9
Searching array position: 8
Searching array position: 7
Searching array position: 6
The target 'mouse' found at array index: 6