代码
//顺序查找
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef int ElemType;
typedef struct {
ElemType *elem;//整形指针,申请的堆空间的起始地址存入elem
int TableLen;//存储动态数组里边元素的个数
}SSTable;
void ST_Init(SSTable &ST,int len)
{
//多申请了一个位置,为了存哨兵,不使用哨兵也可以,为了与王道书保持一致
ST.TableLen = len + 1;
ST.elem = (ElemType*) malloc(sizeof(ElemType)*ST.TableLen);
int i;
srand(time(NULL));//随机数生成
for(i = 1;i < ST.TableLen;i++){//因为第0个是哨兵,所以从1随机
ST.elem[i] = rand() % 100;//为了得到的数在0-99之间
}
}
void ST_print(SSTable ST)
{
//从第1个下标开始打印,因为0号位置是哨兵
for(int i = 1;i < ST.TableLen;i++){
printf("%3d",ST.elem[i]);
}
printf("\n");
}
int Search_Seq(SSTable ST,ElemType key)
{
ST.elem[0] = key;//让零号元素作为哨兵
int i;
for(i = ST.TableLen-1;ST.elem[i]!=key;--i);
return i;
}
int main()
{
SSTable ST;
ST_Init(ST,10);
int pos;//存储查询元素的位置
ST_print(ST);
ElemType key;
printf("请输入要搜索的key值:\n");
scanf("%d",&key);
pos = Search_Seq(ST,key);
if(pos)
printf("查找成功 位置为 %d\n",pos);
else
printf("查找失败\n");
return 0;
}
示例输入输出
79 14 70 70 23 56 31 98 10 68
请输入要搜索的key值:
3
查找失败
58 31 26 66 29 94 94 79 72 87
请输入要搜索的key值:
58
查找成功 位置为 1
23 24 62 12 12 93 7 70 24 97
请输入要搜索的key值:
97
查找成功 位置为 10