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

来源:互联网 发布:淘宝家具运营方案 编辑:程序博客网 时间:2024/05/30 05:18

问题及代码:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /*       
  2. * Copyright (c)2016,烟台大学计算机与控制工程学院       
  3. * All rights reserved.       
  4. * 文件名称:项目1.cpp       
  5. * 作    者:泮春宇      
  6. * 完成日期:2016年12月16日       
  7. * 版 本 号:v1.0        
  8. *问题描述:认真阅读并验证分块查找算法。 
  9. *输入描述:无       
  10. *程序输出:测试数据       
  11. */       


 

分块查找代码:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  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.     KeyType y=90;  
  49.     for (i=0; i<n; i++)    
  50.         R[i].key=a[i];    
  51.     j=IdxSearch(I,m,R,n,x);    
  52.     if (j!=0)    
  53.         printf("%d是第%d个数据\n",x,j);    
  54.     else    
  55.         printf("#未找到%d\n",x);    
  56.     j=IdxSearch(I,m,R,n,y);    
  57.     if (j!=0)    
  58.         printf("%d是第%d个数据\n",y,j);    
  59.     else    
  60.         printf("未找到%d\n",y);    
  61.     return 0;    
  62. }  



 

运算结果:

 

 知识点总结:

分块查找的实践。

学习心得:

分块查找又叫索引顺序查找,是一种性能介于顺序查找和折半查找之间的查找方法。应该区别好三种查找方法,并且掌握。

0 0