/*exp10-1.cpp*/
#include <stdio.h>
#define MAXL 100/*定义表中最多记录个数*/
typedef int KeyType;
typedef char InfoType[10];
typedef struct
{
KeyType key;/*KeyType为关键字的数据类型*/
InfoType data;/*其他数据*/
}NodeType;
typedef NodeType SeqList[MAXL];/*顺序表类型*/
int SeqSearch(SeqList R,int n,KeyType k)/*顺序查找算法*/
{
int i=0;
while(i<n && R[i].key!=k)/*从表头往后找*/
{
printf("%d ",R[i].key);/*输出查找过的元素*/
i++;
}
if(i>=n)
return -1;/*从未找到时返回-1*/
else
{
printf("%d ",R[i].key);
return i;/*找到时返回其位置*/
}
}
void main()
{
SeqList R;
int n=10;
KeyType k=5;
int a[]={3,6,2,10,1,8,5,7,4,9},i;
for(i=0;i<n;i++)/*建立顺序表*/
R[i].key=a[i];
printf("\n");
if(SeqSearch(R,n,k)!=-1)
printf("\n元素%d的位置是%d\n",k,SeqSearch(R,n,k));
else
printf("\n元素%d不在表中\n",k);
printf("\n");
}
#include <stdio.h>
#define MAXL 100/*定义表中最多记录个数*/
typedef int KeyType;
typedef char InfoType[10];
typedef struct
{
KeyType key;/*KeyType为关键字的数据类型*/
InfoType data;/*其他数据*/
}NodeType;
typedef NodeType SeqList[MAXL];/*顺序表类型*/
int SeqSearch(SeqList R,int n,KeyType k)/*顺序查找算法*/
{
int i=0;
while(i<n && R[i].key!=k)/*从表头往后找*/
{
printf("%d ",R[i].key);/*输出查找过的元素*/
i++;
}
if(i>=n)
return -1;/*从未找到时返回-1*/
else
{
printf("%d ",R[i].key);
return i;/*找到时返回其位置*/
}
}
void main()
{
SeqList R;
int n=10;
KeyType k=5;
int a[]={3,6,2,10,1,8,5,7,4,9},i;
for(i=0;i<n;i++)/*建立顺序表*/
R[i].key=a[i];
printf("\n");
if(SeqSearch(R,n,k)!=-1)
printf("\n元素%d的位置是%d\n",k,SeqSearch(R,n,k));
else
printf("\n元素%d不在表中\n",k);
printf("\n");
}