第十四周 验证分块查找算法

/* 
Copyright (c)2016,烟台大学计算机与控制工程学院 
All rights reserved. 
文件名称:验证线性表的分块查找.cpp
作    者:郝环宇
完成日期:2016.12.2
问题描述:验证线性表的分块查找算法
测试输入:查找61、739、200
测试输出:61、739、200所在序列位置。

/*

#include <stdio.h>  
#define MAXL 100    //数据表的最大长度  
#define MAXI 20     //索引表的最大长度  
typedef int KeyType;  
typedef char InfoType[10];  
typedef struct  
{  
    KeyType key;                //KeyType为关键字的数据类型  
    InfoType data;              //其他数据  
} NodeType;  
typedef NodeType SeqList[MAXL]; //顺序表类型  
  
typedef struct  
{  
    KeyType key;            //KeyType为关键字的类型  
    int link;               //指向对应块的起始下标  
} IdxType;  
typedef IdxType IDX[MAXI];  //索引表类型  
  
int IdxSearch(IDX I,int m,SeqList R,int n,KeyType k)  
{  
    int low=0,high=m-1,mid,i;  
    int b=n/m;              //b为每块的记录个数  
    while (low<=high)       //在索引表中进行二分查找,找到的位置存放在low中  
    {  
        mid=(low+high)/2;  
        if (I[mid].key>=k)  
            high=mid-1;  
        else  
            low=mid+1;  
    }  
    //应在索引表的high+1块中,再在线性表中进行顺序查找  
    i=I[high+1].link;  
    while (i<=I[high+1].link+b-1 && R[i].key!=k) i++;  
    if (i<=I[high+1].link+b-1)  
        return i+1;  
    else  
        return 0;  
}  
  
int main()  
{  
    int i,n=56,m=8,j;  
    SeqList R;  
    IDX I= {{24,0},{45,8},{98,16},{158,24},{243,32},{492,40},{856,48}};  
    KeyType a[]= {22,4,23,11,20,2,15,13,30,45,26,34,29,35,26,36,55,98,56,74,61,90,80,96,127,158,116,114,128,113,115,102,184,211,243,188,187,218,195,210,279,307,492,452,408,361,421,399,856,523,704,703,697,535,534,739};  
    KeyType x=200;  
    for (i=0; i<n; i++)  
        R[i].key=a[i];  
    j=IdxSearch(I,m,R,n,x);  
    if (j!=0)  
        printf("%d是第%d个数据\n",x,j);  
    else  
        printf("未找到%d\n",x);  
    return 0;  
}  

运行结果:



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值