分块查找,⼜称索引顺序查找,算法过程如下:
①在索引表中确定待查记录所属的分块(可顺序、可折半)
②在块内顺序查找
特点:块内⽆序、块间有序
#include <iostream>
#include <map> //利用STL中的map来建立索引表
using namespace std;
const int N = 15;
int blocksort(int(&s)[15], map<int, int>& map1, int k);
int main()
{
int k, n = 5;
int s[] = { 1,3,2,0,4,9,6,5,8,7,12,11,10,13,14 }; //每5个数为一块
map<int, int>map1; //建立索引表
map1.insert(map<int, int>::value_type(0, 4)); //三种map的插入方式,效果相同
map1.insert(pair<int, int>(5, 9));
map1.insert(make_pair<int, int>(10, 14));
k = blocksort(s, map1, 11);
if (k == N)
cout << "查找失败" << endl;
else
cout << "元素所在位置:" << k << endl;
}
int blocksort(int(&s)[15], map<int, int>& map1, int k)
{
int index, blocksize = 5;
int i = 0;
//int a[3]; //获取map索引值的两种方法
//way 1
//a[0] = map1.at(0);
//a[1] = map1.at(5);
//a[2] = map1.at(10);
//way 2 迭代方式
//map<int,int>::iterator it;
//for(i,it = map1.begin(); it != map1.end(); ++it,++i)
// a[i] = it->second;
map<int, int>::iterator it;
for (i, it = map1.begin(); it != map1.end(); ++it, ++i) {
if (k <= it->second) {
index = it->first;
break;
}
}
for (i = index; i < index + blocksize; i++)
{
if (s[i] == k)
return i;
}
return N; //false
}