分块查找算法

分块查找是顺序查找和折半查找的结合体!

分块查找充分发挥两者的优点,块之间有序,快内无序;以下代码中,块之间的查找使用折半查找,快内采用顺序查找。

 

//***********************************************************blocksearch.h****************************************************************************

#ifndef BLOCKSEARCH_H_INCLUDED
#define BLOCKSEARCH_H_INCLUDED
typedef struct
{
    int key;
}ElemType;
typedef struct
{
    int value;
    int index;
}Index;
//index为索引表,list为查找表,key为查找的关键字,m为每块的大小,n为查找表的大小,high ,low 分别是索引表的最小和最大下标
int BlockSearch(Index index[],ElemType list[],int low,int high,int key,int m,int n);
#endif // BLOCKSEARCH_H_INCLUDED

//****************************************************************blocksearch.cpp**********************************************************************

#include "blocksearch.h"
int BlockSearch(Index index[],ElemType list[],int low,int high,int key,int m,int n)
{
    int mid = 0;
    while(low<=high)
    {
        mid = (low+high)/2;
        if(index[mid].value<key)
            low = mid +1;
        else//= in the high
            high = mid-1;
    }//high+1 is the position to search...
    int position = high+1;
    int i=index[position].index;
    for(;i<=index[position].index+m-1&&i<n;i++)
    {
        if(list[i].key==key)
            break;
    }
    if(i<=index[position].index+m-1&&i<n)
    return i;
    else
    return -1;//error
}

 

//************************************************************main.cpp********************************************************************

#include <iostream>
#include "blocksearch.h"
using namespace std;

int main()
{

    Index index[] = {{10,0},{20,5},{30,10},{40,15}};
    ElemType list[] ={{1},{5},{6},{9},{10},{11},{15},{16},{19},{20},{21},{25},{26},{29},{30},{31},{35},{36},{39},{40}};
    for(int i=0;i<20;i++)
    {
        cout<<list[i].key<<"\t"<<BlockSearch(index,list,0,3,list[i].key,5,20)<<endl;
    }
    return 0;
}

//***************************测试结果*************************************

1       0
5       1
6       2
9       3
10      4
11      5
15      6
16      7
19      8
20      9
21      10
25      11
26      12
29      13
30      14
31      15
35      16
36      17
39      18
40      19

Process returned 0 (0x0)   execution time : 0.250 s
Press any key to continue.

//*************************************测试结果***************************************

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值