首页 > 解决方案 > 在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

我如何计算找到该数字的次数?

标签: javaif-statementcountreturndo-while

解决方案


您可以使用一个简单的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;

推荐阅读