【发布时间】:2015-06-10 00:41:24
【问题描述】:
我正在尝试在 c++ 上创建线性搜索算法,但我的代码中的 linearSearch 函数遇到了一些问题。这是一个简单的 for 循环,我看不出问题出在哪里,我要求用户输入一个键,如果它是数组中的一个键,那么它应该给出正确的位置,但它没有。任何人都可以看到我在实施中出了什么问题吗?
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int linearSearch(int arr[],int size, int key){
for(int i = 0; i < size; ++i){
if(key == arr[i]){
return i;
}else{
return -1;
}
}
}
int main() {
const int size = 20;
int numbers[size];
srand((unsigned) time(0));
for(int i = 0; i < size; ++i){
numbers[i] = (rand() % 100) + 1;
cout << numbers[i] << " ";
}
cout << endl;
int key;
cout << "Enter a key to search for: " << endl;
cin >> key;
int retValue = linearSearch(numbers,size,key);
if(retValue >= 0){
cout << "Key found at position " << retValue << endl;
}else{
cout << "Key not found" << endl;
}
return 0;
}
【问题讨论】:
-
只是 FWIW,
std::find已经提供了线性搜索。
标签: c++