#include<stdio.h>
#include<malloc.h>
typedef int ElemType;
typedef struct
{
ElemType *elem;
int length;
}SSTable;
void Creat_Seq(SSTable &ST,int n)
{
int i,temp;
ST.elem=(ElemType*)malloc(n*sizeof(ElemType));
if(!(ST).elem)
{
printf("ERROR\n");
return ;
}
for(i=0;i<n;i++)
{
scanf("%d",&temp);
ST.elem[i]=temp;
}
ST.length=n;
}
int Search_bin(SSTable ST,ElemType key)
{
int low=0,high,mid;high=ST.length;
while(low<=high)
{
mid=(low+high)/2;
if(key==ST.elem[mid])
return mid;
else
if(key<ST.elem[mid])
high=mid-1;
else
low=mid+1;
}
return -1;
}
int main()
{
SSTable ST;
int loc,key,n;
scanf("%d",&n);
Creat_Seq(ST,n);
scanf("%d",&key);
loc=Search_bin(ST,key);
if(loc!=-1)
printf("The element position is %d.\n",loc);
else
printf("The element is not exist.\n");
return 0;
}
折半查找

最新推荐文章于 2025-09-06 21:38:00 发布