顺序查找算法

来源:百度知道 编辑:UC知道 时间:2024/06/01 00:57:37

#include <stdio.h>
#include <stdlib.h>

#define MAX_LENGTH 100
typedef int KeyType;

typedef struct {
KeyType *elem;
int length;
}SSTable; //顺序表的存储结构

/*
此算法比第二个算法多了一个判定i是否出界的流程,对于查找数目较少的情况,
二者查找时间相差不大,对于存在大量数据时,该算法的主要查找时间消耗再判
定是否出界上,所以第二个算法明显比第一个算法好,唯一增加的就是一个“哨兵”
数据。
int Search_Seq(SSTable ST, KeyType key){
int i;
for(i=1; i<=ST.length && ST.elem[i] != key; i++ )
;
if(i<=ST.length)
return i;
else
return 0;
}
*/

int Search_Seq(SSTable ST, KeyType key){
int i;
ST.elem[0] = key; //“哨兵”,如果顺序表中不存在要查找的数据的话,则查找指针必定指向该哨兵
for(i = ST.length; ST.elem[i] != key; i--)
;
return i; //找到的话,则i != 0,否则i = 0
}

void main()
{
int i, key;
SSTable T;
T.elem = (KeyType *)malloc(sizeof(KeyType));
printf("How Many Entries Do You Want input\n");
sca