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

  1. /*   
  2. * Copyright (c)2016,烟台大学计算机与控制工程学院   
  3. * All rights reserved.   
  4. * 文件名称:项目1-2.cbp   
  5. * 作    者:朱建豪  
  6. * 完成日期:2016年12月9日   
  7. * 版 本 号:v1.0   
  8.    
  9. * 问题描述:验证分块查找算法   
  10.    
  11. * 输入描述:无   
  12. * 程序输出:测试数据   
  13. */     
代码:

[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. typedef struct    
  13. {    
  14.     KeyType key;            //KeyType为关键字的类型    
  15.     int link;               //指向对应块的起始下标    
  16. } IdxType;    
  17. typedef IdxType IDX[MAXI];  //索引表类型    
  18. int IdxSearch(IDX I,int m,SeqList R,int n,KeyType k)    
  19. {    
  20.     int low=0,high=m-1,mid,i;    
  21.     int b=n/m;              //b为每块的记录个数    
  22.     while (low<=high)       //在索引表中进行二分查找,找到的位置存放在low中    
  23.     {    
  24.         mid=(low+high)/2;    
  25.         if (I[mid].key>=k)    
  26.             high=mid-1;    
  27.         else    
  28.             low=mid+1;    
  29.     }    
  30.     //应在索引表的high+1块中,再在线性表中进行顺序查找    
  31.     i=I[high+1].link;    
  32.     while (i<=I[high+1].link+b-1 && R[i].key!=k) i++;    
  33.     if (i<=I[high+1].link+b-1)    
  34.         return i+1;    
  35.     else    
  36.         return 0;    
  37. }    
  38. int main()    
  39. {    
  40.     int i,n=56,m=7,j;    
  41.     SeqList R;    
  42.     IDX I= {{22,0},{45,8},{98,16},{158,24},{243,32},{492,40},{856,48}};    
  43.     KeyType a[]= {22 ,4  ,23 ,11 ,20 ,2  ,15 ,13 ,    
  44.                   30 ,45 ,26 ,34 ,29 ,35 ,26 ,36 ,    
  45.                   55 ,98 ,56 ,74 ,61 ,90 ,80 ,96 ,    
  46.                   127,158,116,114,128,113,115,102,    
  47.                   184,211,243,188,187,218,195,210,    
  48.                   279,307,492,452,408,361,421,399,    
  49.                   856,523,704,703,697,535,534,739};    
  50.     KeyType x=200;    
  51.     for (i=0; i<n; i++)    
  52.         R[i].key=a[i];    
  53.     j=IdxSearch(I,m,R,n,x);    
  54.     if (j!=0)    
  55.         printf("%d是第%d个数据\n",x,j);    
  56.     else    
  57.         printf("未找到%d\n",x);    
  58.     return 0;    
  59. }    
运行结果:

查找61时

查找739时

查找200时

知识点总结:

验证分块查找算法


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值