#include <stdio.h>
#include <string>
#include <stdlib.h>
const int MaxSize=50;
typedef int KeyType;
typedef int ElemType;
typedef struct
{
KeyType key;
ElemType data;
} SqType;
int BinSearch(SqType R[],int n,KeyType k)
{ int low=0,high=n-1,mid,y=0;
while (low<=high)
{
mid=(low+high)/2;
y++;
if (R[mid].key==k)
{
printf("\t\t在[%d..%d]查找,与R[%d].key=%d比较,相等\n",low,high,mid,R[mid].key);printf("共比较%d次\n",y);
return mid+1;
}
else if(R[mid].key>k)
{ printf("\t\t在[%d..%d]查找,与R[%d].key=%d比较,不相等\n",low,high,mid,R[mid].key);
high=mid-1;
}
else
{
printf("\t\t在[%d..%d]查找,与R[%d].key=%d比较,不相等\n",low,high,mid,R[mid].key);
low=mid+1;
}
}
printf("共比较%d次\n",y);
return 0;
}
void main()
{
int a[]={12, 24, 35, 47, 50, 62, 83, 115}, b;
SqType R[MaxSize];
printf("查找表:");
for(int i=0; i<8; i++)
{ R[i].key=a[i];
printf("%4d",R[i].key);
}
printf("\n");
int c;
printf("请输入你要查找的关键字:");
scanf("%d",&c);
printf("\n查找关键字%d:\n\n",c);
b=BinSearch(R , 8 , c);
if(b==0) printf("查找%d失败\n",c);
else printf("查找%d成功\n",c);
int f;
printf("请输入你要查找的关键字:");
scanf("%d",&f);
printf("\n查找关键字%d:\n\n",f);
b=BinSearch(R , 8 , f);
if(b==0) printf("查找%d失败\n",f);
else printf("查找%d成功,逻辑序号是%d\n",f,b);
int h;
printf("请输入你要查找的关键字:");
scanf("%d",&h);
printf("\n查找关键字%d:\n\n",h);
b=BinSearch(R , 8 , h);
if(b==0) printf("查找%d失败\n",h);
else printf("查找%d成功,逻辑序号是%d\n",h,b);
}
编写一个函数,实现折半查找算法。实现在8个数据元素的有序表( 12, 24, 35, 47, 50, 62, 83, 115 )中采用折半查找方法,查找关键字90,47和35。
最新推荐文章于 2022-11-19 21:08:19 发布