仅仅作为自己的存储代码,具体,还需要自己分析!谢谢
#include <stdio.h>
#define MAX 21
int n;
//8.3
int BinSearch(int A[],int k)
{
int low=1,high=MAX,mid;
n=1;
while(low<=high)
{
mid=(low+high)/2;
printf("当前mid处于:%d\n",mid);
if(A[mid]==k)
return mid;
if(A[mid]>k)
high=mid-1;
else//A[mid]<k
low=mid+1;
n++;
}
return 0;
}
int NormalSearch(int A[],int k)
{
int i=0;
n=1;
while(i<MAX)
{
if(A[i]==k)
return i;
i++;
n++;
}
return 0;
}
void main()
{
int ps,k=67;
int A[MAX]={0,2,4,5,7,8,11,24,25,27,31,35,39,41,46,47,55,60,67,82,108};
//普通查找
printf("\n---普通查找---\n");
ps=NormalSearch(A,k);
printf("\n总比较次数:%d\n",n);
if(ps!=0)
printf("在第%d个位置找到关键字%d。\n",ps,k);
else
printf("未找关键字%d\n",k);
//二分查找
printf("\n---二分查找---\n",n);
ps=BinSearch(A,k);
printf("\n总比较次数:%d\n",n);
if(ps!=0)
printf("在第%d个位置找到关键字%d。\n",ps,k);
else
printf("未找关键字%d\n",k);
}