分块查找是顺序查找和折半查找的结合体!
分块查找充分发挥两者的优点,块之间有序,快内无序;以下代码中,块之间的查找使用折半查找,快内采用顺序查找。
//***********************************************************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.
//*************************************测试结果***************************************