第十四周项目1(2)——验证分块查找算法

来源:互联网 发布:php 36进制 编辑:程序博客网 时间:2024/05/01 20:14
  1. /*       
  2. * Copyright (c)2016,烟台大学计算机与控制工程学院       
  3. * All rights reserved.       
  4. * 文件名称:wu.cpp       
  5. * 作    者:武昊       
  6. * 完成日期:2016年12月8日       
  7. * 版 本 号:v1.0        
  8. *问题描述:认真阅读并验证分块查找算法。 
  9. *输入描述:无       
  10. *程序输出:测试数据       
  11. */
  1. #include <stdio.h>  
  2. #define MAXL 100    //数据表的最大长度  
  3. #define MAXI 20     //索引表的最大长度  
  4. typedef int KeyType;  
  5. typedef char InfoType[10];  
  6. typedef struct  
  7. {  
  8.     KeyType key;                //KeyType为关键字的数据类型  
  9.     InfoType data;              //其他数据  
  10. } NodeType;  
  11. typedef NodeType SeqList[MAXL]; //顺序表类型  
  12.   
  13. typedef struct  
  14. {  
  15.     KeyType key;            //KeyType为关键字的类型  
  16.     int link;               //指向对应块的起始下标  
  17. } IdxType;  
  18. typedef IdxType IDX[MAXI];  //索引表类型  
  19.   
  20. int IdxSearch(IDX I,int m,SeqList R,int n,KeyType k)  
  21. {  
  22.     int low=0,high=m-1,mid,i;  
  23.     int b=n/m;              //b为每块的记录个数  
  24.     while (low<=high)       //在索引表中进行二分查找,找到的位置存放在low中  
  25.     {  
  26.         mid=(low+high)/2;  
  27.         if (I[mid].key>=k)  
  28.             high=mid-1;  
  29.         else  
  30.             low=mid+1;  
  31.     }  
  32.     //应在索引表的high+1块中,再在线性表中进行顺序查找  
  33.     i=I[high+1].link;  
  34.     while (i<=I[high+1].link+b-1 && R[i].key!=k) i++;  
  35.     if (i<=I[high+1].link+b-1)  
  36.         return i+1;  
  37.     else  
  38.         return 0;  
  39. }  
  40.   
  41. int main()  
  42. {  
  43.     int i,n=25,m=5,j;  
  44.     SeqList R;  
  45.     IDX I= {{14,0},{34,5},{66,10},{85,15},{100,20}};  
  46.     KeyType a[]= {8,14,6,9,10,22,34,18,19,31,40,38,54,66,46,71,78,68,80,85,100,94,88,96,87};  
  47.     KeyType x=85;  
  48.     for (i=0; i<n; i++)  
  49.         R[i].key=a[i];  
  50.     j=IdxSearch(I,m,R,n,x);  
  51.     if (j!=0)  
  52.         printf("%d是第%d个数据\n",x,j);  
  53.     else  
  54.         printf("未找到%d\n",x);  
  55.     return 0;  
  56. }  


0 0