我編寫了一個Java類的程序,我正在爲一個特定的目標搜索字符串數組。程序從數組的開始到數組的結尾搜索目標,然後從數組的末尾搜索數組的開始。我應該測試兩種搜索的速度,以查看哪一個更快。我如何測試這個?如何測試字符串數組搜索的速度?
下面是程序:
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);
}
}
這裏是輸出:
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
+1正確的測試/基準測試套件通常比代碼中的開發工件的擴散更適合。 – user2864740