二分查找技术作为一种查找技术。与顺序查找,效率高很多!
#include<stdio.h>
#define MAXL 100
typedef struct
{
int key;
}NodeType;
typedef NodeType SeqList[MAXL];
/********二分查找************/
int BinSearch(SeqList &R,int n,int k)
{
int low=0,high=n-1,mid;
while(low<=high)
{ mid=(low+high)/2;
if(R[mid].key==k)
return mid;
if(R[mid].key>k)
high=mid-1;
else
low=mid+1;
}
return -1;
}
/********顺序查找*************/
int BinSearch2(SeqList &R,int n,int k)
{
int i=1;
while(i<n&&R[i].key!=k)i++;
if(i>=n)return 0;
else
return i;
}
int main()
{ int i;int n,k;
SeqList R;
while(scanf("%d",&n)!=EOF)
{ scanf("%d",&k);
for(i=1;i<=n;i++)
R[i].key=i;
printf("二分查找结果:%d/n",BinSearch(R,n,k));
printf("顺序查找结果:%d/n",BinSearch2(R,n,k));
}
return 0;
}