题目描述
1、定义一个顺序存储结构或者数组
2、输入数组元素的个数
3、依次输入数组中的元素值
4、中间处理:顺序查找,通过顺序查找:理解查找成功的ASL和查找失败的ASL。
4、输出:各个数组元素值,且输出顺序查找的结果。
PS:本题考查顺序查找,当然取巧的方式几行代码也能实现,不过不是我们推荐的方式。
PS:可以扩展,给个数组之外的值,输出对应的查找结果,看是否能查到。
输入
5 //数组大小
1 3 9 11 0 //数组元素个数
输出
1 is exist, location is 1
3 is exist, location is 2
9 is exist, location is 3
11 is exist, location is 4
0 is exist, location is 5
样例输入
3
1 5 4
样例输出
1 is exist, location is 1
5 is exist, location is 2
4 is exist, location is 3
代码实现
#include <iostream>
using namespace std;
typedef int KeyType;
typedef int InfoType;
typedef struct
{
KeyType key;
InfoType data;
}RecType;
int SeqSearch(RecType R[], int n, KeyType k)
{
int i = 0;
while(i < n && R[i].key != k)
{
i++;
}
if(i >= n)
{
return -1;
}
else
{
return i+1;
}
}
int main()
{
int loca = 0;
//数组长度
int n = 0;
cin>>n;
RecType arry[n];
for(int i = 0; i < n; i++)
{
cin>>arry[i].key;
}
for(int i = 0; i < n; i++)
{
loca = SeqSearch(arry, n, arry[i].key);
cout<< arry[i].key <<" is exist, location is "<< loca <<endl;
}
return 0;
}