第十四周 项目1验证算法

来源:互联网 发布:电影特效知乎 编辑:程序博客网 时间:2024/06/01 08:20
  1. #include <stdio.h>  
  2. #define MAXL 100  
  3. typedef int KeyType;  
  4. typedef char InfoType[10];  
  5. typedef struct  
  6. {  
  7.     KeyType key;                //KeyType为关键字的数据类型  
  8.     InfoType data;              //其他数据  
  9. } NodeType;  
  10. typedef NodeType SeqList[MAXL];     //顺序表类型  
  11.   
  12. int BinSearch(SeqList R,int n,KeyType k)  
  13. {  
  14.     int low=0,high=n-1,mid;  
  15.     while (low<=high)  
  16.     {  
  17.         mid=(low+high)/2;  
  18.         if (R[mid].key==k)      //查找成功返回  
  19.             return mid+1;  
  20.         if (R[mid].key>k)       //继续在R[low..mid-1]中查找  
  21.             high=mid-1;  
  22.         else  
  23.             low=mid+1;          //继续在R[mid+1..high]中查找  
  24.     }  
  25.     return 0;  
  26. }  
  27.   
  28. int main()  
  29. {  
  30.     int i,n=10;  
  31.     int result;  
  32.     SeqList R;  
  33.     KeyType a[]= {1,3,9,12,32,41,45,62,75,77},x=75;  
  34.     for (i=0; i<n; i++)  
  35.         R[i].key=a[i];  
  36.     result = BinSearch(R,n,x);  
  37.     if(result>0)  
  38.         printf("序列中第 %d 个是 %d\n",result, x);  
  39.     else  
  40.         printf("木有找到!\n");  
  41.     return 0;  
  42. }  

递归的折半查找

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #define MAXL 100  
  3. typedef int KeyType;  
  4. typedef char InfoType[10];  
  5. typedef struct  
  6. {  
  7.     KeyType key;                //KeyType为关键字的数据类型  
  8.     InfoType data;              //其他数据  
  9. } NodeType;  
  10. typedef NodeType SeqList[MAXL];     //顺序表类型  
  11.   
  12. int BinSearch1(SeqList R,int low,int high,KeyType k)  
  13. {  
  14.     int mid;  
  15.     if (low<=high)      //查找区间存在一个及以上元素  
  16.     {  
  17.         mid=(low+high)/2;  //求中间位置  
  18.         if (R[mid].key==k) //查找成功返回其逻辑序号mid+1  
  19.             return mid+1;  
  20.         if (R[mid].key>k)  //在R[low..mid-1]中递归查找  
  21.             BinSearch1(R,low,mid-1,k);  
  22.         else              //在R[mid+1..high]中递归查找  
  23.             BinSearch1(R,mid+1,high,k);  
  24.     }  
  25.     else  
  26.         return 0;  
  27. }  
  28.   
  29. int main()  
  30. {  
  31.     int i,n=10;  
  32.     int result;  
  33.     SeqList R;  
  34.     KeyType a[]= {1,3,9,12,32,41,45,62,75,77},x=75;  
  35.     for (i=0; i<n; i++)  
  36.         R[i].key=a[i];  
  37.     result = BinSearch1(R,0,n-1,x);  
  38.     if(result>0)  
  39.         printf("序列中第 %d 个是 %d\n",result, x);  
  40.     else  
  41.         printf("木有找到!\n");  
  42.     return 0;  

  1. }  

1 0
原创粉丝点击