思路很简单,平均要查找(n+1)/2次,复杂度为O(n)
代码实现:
#include <iostream>
using namespace std;
int SequentialSearch(int *a, const int n, int x){
int i;
for (i = 0; i < n; ++i){//循环数组中每一个数,与要查找的数进行对比
if (a[i] == x){
return i;//若找到返回数组索引
}
}
if (i == n){
return -1;//没找到返回-1
}
}
int main(){
int a[] = { 2, 4, 6, 8, 0, 1, 3, 5, 7, 9 };
int size = sizeof(a) / sizeof(a[0]);//取数组的大小
int numToFind;//输入要查找的数
cout << "Please input a number you want to find:";
cin >> numToFind;
int result;
result = SequentialSearch(a, size, numToFind);//调用函数
if (result == -1){
cout << "Not found." << endl;
}
else{
cout << "在m[" << result << "]里找到" << numToFind << endl;
}
return 0;
}