顺序查找(通用算法)
源程序:
#include <stdio.h>
#define MaxSize 8
typedef struct
{
int stuno;
char stuname[20];
}TableElem; //基本分量结构体类型
TableElem stu[]={{1001,"zhang"},{1009,"wang"},{2005,"sun"},{2008,"zheng"},
{3001,"liu"},{3005,"lai"},{4003,"qin"},{4400,"ren"}};
typedef struct
{
TableElem elem[MaxSize];
int n;
}SqTable; //学生的结构体
//顺序查找函数的通用写法
int searchsqtable(SqTable T,int key)
{
T.elem[0].stuno=key;
int i=T.n;
while(T.elem[i].stuno!=key)
i--;
return i;
}
int main()
{
SqTable seq;
int i;
for(i=0;i<MaxSize;i++)
{
seq.elem[i]=stu[i]; //初始化学生数组elem[i]
}
seq.n=MaxSize;
int num,mm;
printf("请输入要查找的学号:");
scanf("%d",&num);
mm=searchsqtable(seq,num);
printf("此人在顺序表中的位置是:%d
",mm+1);
return 1;
}
运行结果: