第十三周项目三

来源:互联网 发布:大数据架构师考试 编辑:程序博客网 时间:2024/06/11 16:39
/*
Copyright (c++) 2017,烟台大学计算机与控制工程学院
文件名称:jcy
作 者:贾存钰
完成日期:2017年11月29日
问题描述:分块查找

*/

[cpp] view plain copy
  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. }