#include<stdio.h>
#include<stdlib.h>
#define ElemType int
#define KeyType int
#define max 20
typedef struct {
ElemType *elem;
int length;
}SStable;//以顺序表作为基础的折半查找
void creat(SStable &st)//初始化
{
st.elem=(ElemType*)malloc(max*sizeof(SStable));
st.elem[0]=5;
st.elem[1]=13;
st.elem[2]=19;
st.elem[3]=21;
st.elem[4]=37;
st.elem[5]=56;
st.elem[6]=64;
st.elem[7]=75;
st.elem[8]=80;
st.elem[9]=88;
st.elem[10]=92;
st.length=11;
}
bool EQ(int i,int key)
{
if(i==key)
return 1;
else return 0;
}
bool LT(int i,int j)
{
if(i<j)
return 1;
else return 0;
}
int Search_Bin(SStable st,int key) //折半查找算法
{
int low,high,mid;
low =1;high=st.length;
while(low<=high)
{
mid=(low+high)/2;
if(EQ(st.elem[mid],key)) return mid;
else if(LT(key,st.elem[mid])) high=mid-1;//如果中间记录比key大.high就成为mid-1,即要在上半部分找
else low=mid+1; //如果中间记录比key小,就要在下半部分找
}
return 0;
}
void main()
{
int i,j;
SStable st;
creat(st);
printf("请输入您要查询的数字");
scanf("%d",&i);
j=Search_Bin(st,i);
if(j==0) printf("没有你要查询的");
else printf("您要查询的数字在数组中的第%d个位置处",j-1);
getchar();
getchar();
}
#include<stdlib.h>
#define ElemType int
#define KeyType int
#define max 20
typedef struct {
ElemType *elem;
int length;
}SStable;//以顺序表作为基础的折半查找
void creat(SStable &st)//初始化
{
st.elem=(ElemType*)malloc(max*sizeof(SStable));
st.elem[0]=5;
st.elem[1]=13;
st.elem[2]=19;
st.elem[3]=21;
st.elem[4]=37;
st.elem[5]=56;
st.elem[6]=64;
st.elem[7]=75;
st.elem[8]=80;
st.elem[9]=88;
st.elem[10]=92;
st.length=11;
}
bool EQ(int i,int key)
{
if(i==key)
return 1;
else return 0;
}
bool LT(int i,int j)
{
if(i<j)
return 1;
else return 0;
}
int Search_Bin(SStable st,int key) //折半查找算法
{
int low,high,mid;
low =1;high=st.length;
while(low<=high)
{
mid=(low+high)/2;
if(EQ(st.elem[mid],key)) return mid;
else if(LT(key,st.elem[mid])) high=mid-1;//如果中间记录比key大.high就成为mid-1,即要在上半部分找
else low=mid+1; //如果中间记录比key小,就要在下半部分找
}
return 0;
}
void main()
{
int i,j;
SStable st;
creat(st);
printf("请输入您要查询的数字");
scanf("%d",&i);
j=Search_Bin(st,i);
if(j==0) printf("没有你要查询的");
else printf("您要查询的数字在数组中的第%d个位置处",j-1);
getchar();
getchar();
}