查找树-------二分查找

#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();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值