顺序查找和二分查找的区别_顺序查找
来源: 互联网      时间:2023-05-20 14:22:22


(资料图片仅供参考)

1、#include #include #define MAX_LENGTH 100typedef int KeyType;typedef struct { KeyType *elem; int length; }SSTable; //顺序表的存储结构/*此算法比第二个算法多了一个判定i是否出界的流程,对于查找数目较少的情况,二者查找时间相差不大,对于存在大量数据时,该算法的主要查找时间消耗再判定是否出界上,所以第二个算法明显比第一个算法好,唯一增加的就是一个“哨兵”数据。

2、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"); scanf("%d", &T.length); for(i=1; i<=T.length; i++){ printf("Please input the %dth entries ", i); scanf("%d", &T.elem[i]); } for (i=1; i<=T.length; i++) printf("%5d",T.elem[i]); //显示已经输入的所有数据 printf("Please input the data you want to search"); scanf("%d", &key); i = Search_Seq(T,key); printf("the search data is locate the %dth(0 indicate can not find)",i); }。

本文就为大家分享到这里,希望小伙伴们会喜欢。

标签:

广告

X 关闭

广告

X 关闭