java - 在java中使用线性搜索计算比较
问题描述
我的代码是:
public static int linearSearch(int array[], int key){
/*
Description: Performs linear search on an array for a specified value
Parameters: int array of values and int key which item to be searched
Returns: int indicating how many times number is found
*/
boolean found = false;
int numberOfComparisons = 0;
int index = 0;
// Loop which breaks if number found or all numbers checked
do{
// Check key against current array value
if (array[index] == key){
found = true;
}// if
index++;
numberOfComparisons++;
}
while(found && (index < array.length));
// Return statements
System.out.println("Number of comparisons with linear search: " + numberOfComparisons);
if (found) return numberOfComparisons;
else return -1;
}// linear search
我如何计算找到该数字的次数?
解决方案
您可以使用一个简单的for
循环来遍历整个数组一次并检查每个元素。作为循环条件的一部分使用found
是没有意义的,因为必须至少遍历整个数组一次才能计算特定元素出现的次数。
int times = 0;
for(int i = 0; i < array.length; i++){
if(array[i] == key){
++times;
}
}
return times;
可以使用 for-each 循环来简化这一点,因为不需要索引。
int times = 0;
for(int num: array){
if(num == key){
++times;
}
}
return times;
推荐阅读
- javascript - 如何呈现包含打开和未关闭标签的组件?反应.js
- python - 使用 Nginx 在不同端口上的多个 gunicorn 应用程序
- php - Laravel 在许多对象调度作业上的长循环正在超时。
- php - FullCalendar 在使用 Ajax 时返回错误
- java - 按 ID 对 JSON 数组进行排序
- php - 用“span”元素替换“div”元素
- python - 带有字典 `count_if=1` 的 Pandas 聚合被忽略。
- android - 在 iOS 设备上不可见的 Gmail 插件
- java - Rest Assured - 使用 RestAssured 进行测试时出现操作超时错误。但是相同的端点在浏览器中工作正常
- list - 在 Scheme 中搜索定义的列表