【问题标题】:count comparisons using linear search in java在java中使用线性搜索计算比较
【发布时间】:2020-11-17 07:26:16
【问题描述】:

我的代码是:

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

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

【问题讨论】:

  • 我的回答对你有用吗?

标签: java if-statement count return do-while


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-09-23
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    相关资源
    最近更新 更多