【发布时间】: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