第十三周项目一

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

运行结果:

学习心得:

学会了运用折半查找法,验证了折半查找法的算法。

原创粉丝点击