#include <iostream>
using namespace std;
int seqSearch(int a[], int n, int key)
{
int i = 0;
while(i < n && a[i] != key)
i++;
//跳出循环的条件必然为i等于n或者a[i]等于key
if(n == i) //也就是说i为n-1时,a[i]不等于key
return -1;
return i;
}
int main()
{
int a[] = {4, 5, 3, 2, 1};
int result = seqSearch(a, 5, 2);
if(-1 == result)
cout << "no!" << endl;
else
cout << "yes! location: " << result + 1 << endl;
return 0;
}
顺序查找
本文转载:CSDN博客