顺序查找(监视哨)、折半查找
顺序查找
不带监视哨
int Search_Seq_1(SSTable S,ElemType key)
{
for(int i=0;i<S.length;i++)
{
if(S.elem[i]==key)
return i;
}
return -1;
}
带监视哨
int Search_Seq_2(SSTable S,ElemType key)
{
S.elem[0]=key;
int i=S.length-1;
while(S.elem[i]!=key)
{
i--;
}
return i;
}
不带监视哨的写法中,没循环一次都要判断两个条件1、i<S.length 2、S.elem[i]==key;而带监视哨的写法没循环一次仅要判断S.elem[i]!=key即可,当元素个数大于1000时,程序运行时间可几乎减少一半;
折半查找
折半查找仅适用于对有序表的查找; 查找原理是附设三个指针,low,high,mid;初始化分别执行表头、表尾、表的中间元素,当查找元素key等于mid所指的时,即查找成功,当所指元素小于它时,说明key在【low,mid】的区间内,此时令high=mid-1,mid=(low+high)/2;相反当大于时,low=mid+1,mid=(low+high)/2,直到查找成功;
int Search_Bin(SSTable S,ElemType key)
{
int low=0,high=S.length-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(S.elem[mid]==key)
{
return mid;
}
else if(key<S.elem[mid])
high=mid-1;
else
low=mid+1;
}
return -1;
}
完整代码:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define MAXSIZE 100 //查找表的最大存储容量
typedef char ElemType;
//顺序查找表的顺序存储结构
typedef struct
{
ElemType *elem;
int length;
}SSTable;
//查找表初始化
void Init_SSTable(SSTable *S)
{
S->elem=(ElemType *)malloc(MAXSIZE*sizeof(ElemType));
S->length=0;
}
//向查找表输入元素
void Input_SSTable(SSTable *S)
{
char ch;
ElemType e;
while(1)
{
scanf("%c",&e);
S->elem[S->length++]=e;
if((ch=getchar())=='\n')
break;
}
}
//打印查找表元素
void Show_SSTable(SSTable S)
{
for(int i=0;i<S.length;i++)
{
printf("%c ",S.elem[i]);
}
}
//顺序查找(无监视哨的写法)
int Search_Seq_1(SSTable S,ElemType key)
{
for(int i=0;i<S.length;i++)
{
if(S.elem[i]==key)
return i;
}
return -1;
}
//顺序查找(带监视哨的写法)
int Search_Seq_2(SSTable S,ElemType key)
{
S.elem[0]=key;
int i=S.length-1;
while(S.elem[i]!=key)
{
i--;
}
return i;
}
//折半查找
int Search_Bin(SSTable S,ElemType key)
{
int low=0,high=S.length-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(S.elem[mid]==key)
{
return mid;
}
else if(key<S.elem[mid])
high=mid-1;
else
low=mid+1;
}
return -1;
}
int main()
{
SSTable S,*p;p=&S;
Init_SSTable(p);
Input_SSTable(p);
Show_SSTable(S);
int result;
result=Search_Seq_1(S, '4');
printf("\n%d\n",result);
result=Search_Seq_2(S, '4');
printf("%d\n",result);
result=Search_Bin(S, '4');
printf("%d\n",result);
return 0;
}
/* 测试
0 1 2 3 4 5 6
0 1 2 3 4 5 6
4
4
4
Program ended with exit code: 0
*/