顺序查找数据序列中某个特定值的步骤
Step1:输入数据序列data[n]和欲查找值key
Step2:从序列中的最后一个元素开始查找
Step3:若该元素值不等于key,查找前一项.
Step4 :若该元素值等于key,表示查找成功,返回key在序列中的位置,去第六步.
Step5:如果数据全部查找过但未能找到key,表示查找失败,返回0。
Step6:结束
代码如下:
#include <stdio.h>//包含预编译头文件
#include<stdlib.h>
//宏定义
#define Size (L.length+1)*sizeof(KeyType)
typedef int KeyType; //类型别名的定义
typedef struct {
KeyType* elem;
int length;
}SqList;
bool EQ(int i, int j)//判断两个整数是否相等
{
if (i == j) return 1;
else return 0;
}
//函数实现
void Construction(SqList& L) //构造无序序列
{
int i;
printf("input the length of data:\n");
scanf("%d", &L.length);
L.elem = (KeyType*)malloc(Size);
printf("input the key:\n");//输入待查找的关键字
for (i = 1; i <= L.length; i++)
scanf("%d", &L.elem[i]);
}
int Search(SqList L, KeyType key)//查找函数
{
int i;
L.elem[0] = key;
for (i = L.length; !EQ(L.elem[i], key); --i);
return i;
}
int main()
{
KeyType key;
SqList L;
printf("input key:\n");
scanf("%d", &key);//读入要查找的值
Construction(L);//创建待查找数据序列
int position = Search(L, key);//查找
printf("the key is located in %d", position);
return 0;
}