第十三周笔记
第十三周笔记
折半查找法+顺序查找法
1.定义
#include <stdio.h>
#include <stdlib.h>
#define LIST_SIZE 20
#define KeyType int
typedef struct
{
KeyType key;
//OtherType other_data;
}RecordType;
typedef struct
{
RecordType r[LIST_SIZE+1];/*若为顺序查找法,建立r[0]为监视哨单元*/
int length;
}RecordList;
2. 折半查找
int BinSrch(RecordList L,KeyType k) //折半查找法,在有序表中折半查找关键字等于 K 的元素,若找到,返回其位置,否则返回0
{
int low=1;
int high=L.length;
while(low<=high)
{
int mid=(low+high)/2;
if(L.r[mid].key==k)
return(mid);
else if(L.r[mid].key>k)
high=mid-1;
else
low=mid+1;
}
return 0;
}
3.顺序查找法
int SeqSearch(RecordList L,KeyType k) //顺序查找,在顺序表L中查找关键字等于K的元素,若找到,返回位置,若未找到,返回0
{
L.r[0].key=k;
int i=L.length;
while(L.r[i].key!=k)
{
i--;
}
return i;
}
4. 小结
通过实验发现折半查找法在很大的程度上减少了算法的时间复杂度,提高了性能。而顺序查找法要建立一个监视哨,作为查找数据的存放位置,则有效数位要比原来的长度多一,即可实现查找功能。两种方法都很高效。