第十三周项目1(1)

来源:互联网 发布:淘宝上国棉一厂怎么样 编辑:程序博客网 时间:2024/05/29 07:00
  1. /*  
  2. 烟台大学计算机学院  
  3.   
  4. 文件名称:xiangmu.cpp  
  5.   
  6. 作者:张帅
  7.   
  8. 完成日期:2017年11月26日  
  9.   
  10. 问题描述:验证折半查找算法。 
  11.           请用有序表{12,18,24,35,47,50,62,83,90,115,134}作为测试序列, 
  12.           分别对查找90、47、100进行测试。  
  13.   
  14. 输入描述:无 
  15.   
  16. 输出描述:输出查找位置和结果 
  17.   
  18. */   
  19.   
  20.   
  21. #include <stdio.h>  
  22. #define MAXL 100  
  23. typedef int KeyType;  
  24. typedef char InfoType[10];  
  25. typedef struct  
  26. {  
  27.     KeyType key;                //KeyType为关键字的数据类型  
  28.     InfoType data;              //其他数据  
  29. } NodeType;  
  30. typedef NodeType SeqList[MAXL];     //顺序表类型  
  31.   
  32. int BinSearch(SeqList R,int n,KeyType k)  
  33. {  
  34.     int low=0,high=n-1,mid;  
  35.     while (low<=high)  
  36.     {  
  37.         mid=(low+high)/2;  
  38.         if (R[mid].key==k)      //查找成功返回  
  39.             return mid+1;  
  40.         if (R[mid].key>k)       //继续在R[low..mid-1]中查找  
  41.             high=mid-1;  
  42.         else  
  43.             low=mid+1;          //继续在R[mid+1..high]中查找  
  44.     }  
  45.     return 0;  
  46. }  
  47.   
  48. int main()  
  49. {  
  50.     int i,n=10;  
  51.     int result;  
  52.     int result2;  
  53.     int result3;  
  54.     SeqList R;  
  55.     KeyType a[]= {12,18,24,35,47,50,62,83,90,115,134},x=90,y=47,z=100;  
  56.     for (i=0; i<n; i++)  
  57.         R[i].key=a[i];  
  58.     result = BinSearch(R,n,x);  
  59.     if(result>0)  
  60.         printf("序列中第 %d 个是 %d\n",result, x);  
  61.     else  
  62.         printf("木有找到!\n");  
  63.   
  64.           result2 = BinSearch(R,n,y);  
  65.     if(result2>0)  
  66.         printf("序列中第 %d 个是 %d\n",result2, y);  
  67.     else  
  68.         printf("木有找到!\n");  
  69.   
  70.           result3= BinSearch(R,n,z);  
  71.     if(result3>0)  
  72.         printf("序列中第 %d 个是 %d\n",result3, z);  
  73.     else  
  74.         printf("木有找到!\n");  
  75.     return 0;  
  76. }  
原创粉丝点击