查找算法实现
输出在顺序表{1,2,3,4,5,6,7,8,9,10}中采用折半查找方法查找关键字9的过程`
include<stdio.h>
#include<malloc.h>
#define MaxSize 50
typedef int KeyType;
typedef int InfoType;
typedef struct
{
KeyType key;
InfoType data[MaxSize];
}RecType;
void CreateBin(RecType *&R,int A[],int n);
int BinSearch(RecType *R,int n,KeyType k);
int main()
{
int a[]={1,2,3,4,5,6,7,8,9,10};
RecType *R;
int n=10,k=11;
CreateBin(R,a,n);
printf(“顺序表为:[”);
for(int i=0;i<n;i++)
printf("%d,",R->data[i]);
printf("]\n");
while(BinSearch(R,n,k)!=0)
printf("%d",BinSearch(R,n,k));
}
void CreateBin(RecType *&R,int A[],int n)
{
int i=0,k=0;
R=(RecType *)malloc(sizeof(RecType));
while(i<n)
{
R->data[i]=A[i];
k++;i++;
}
}
int BinSearch(RecType *R,int n,KeyType k)
{
int low=0,high=n-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(low!=high)
printf(“此次在这[%d,%d]区间内查询\n”,low,high);
else if(low== high)
printf(“查找成功,该数在数组中的位置为%d”,low);
else
return 0;
if(k==R->data[mid])
return mid+1;
if(kdata[mid])
high=mid-1;
else
low=mid+1;
}
return 0;
}
对于实现这个功能,现在已经可以实现了。第一次发表,如果我哪里有错误或有更好的方法,我也很乐意和你一起讨论。