java字符串数组怎么精准查询_java-如何测试字符串数组搜索的速度?

我为Java类编写了一个程序,该程序用于在String数组中搜索特定目标.程序从数组的开头到数组的结尾搜索目标,然后从数组的结尾到数组的开头搜索目标.我应该测试两种搜索的速度,看看哪个更快.我该如何测试?

这是程序:

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("

Backwards 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值