第十三周项目一

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

运行结果: