第十四周项目1-验证算法

问题及代码:

#include <stdio.h>
#define MAXL 100
typedef int KeyType;
typedef char InforType[10];
typedef struct
{
KeyType key;
InforType data;
}NodeType;
typedef NodeType SeqList[MAXL];
int BinSearch(SeqList R,int n,KeyType k)
{
int low=0,high=n-1,mid;
 while(low<=high)
 {
  mid=(high+low)/2;
  if(R[mid].key==k)
	  return mid+1;
  if(R[mid].key>k)
      high=mid-1;
  else
	  low=mid+1;
 }
 return 0;
}
int main()
{
    int i,n=10;
    int result;
    SeqList R;
    KeyType a[]= {12,18,24,35,47,50,62,83,90,115,134},x;
    for (i=0; i<n; i++)
        R[i].key=a[i];
    result = BinSearch(R,n,x);
	x=90;
    if(result>0)
        printf("序列中第 %d 个是 %d\n",result, x);
    else
        printf("木有找到!\n");
	result = BinSearch(R,n,x);
	x=47;
    if(result>0)
        printf("序列中第 %d 个是 %d\n",result, x);
    else
        printf("木有找到!\n");
	result = BinSearch(R,n,x);

	x=100;
    if(result>0)
        printf("序列中第 %d 个是 %d\n",result, x);
    else
        printf("木有找到!\n");
	result = BinSearch(R,n,x);


    return 0;
}


运行结果:

猜你喜欢

转载自blog.csdn.net/qq_35254240/article/details/53419104