分享下能跑通的分块查找C++代码
//分块查找
int search(int id) {
sort(vec.begin(), vec.end());
int blockSize = 3;
int n = vec.size();
if (n == 0) return -1;
// 计算最大块数
int maxBlock = ceil((double)n / blockSize);
vector<int> maxValues(maxBlock);
// 构建最大关键字表
for (int i = 0; i < maxBlock; ++i) {
int end = min(i * blockSize + blockSize - 1, n - 1);
maxValues[i] = vec[end];
}
// 二分查找最大关键字表确定块号
int blockIndex = -1;
int low = 0, high = maxBlock - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (id <= maxValues[mid]) {
blockIndex = mid;
high = mid - 1;
}
else {
low = mid + 1;
}
}
// 如果块号越界或块内没有目标元素,则返回-1
if (blockIndex == -1 || blockIndex >= maxBlock) return -1;
// 在确定的块内顺序查找目标元素
int start = blockIndex * blockSize;
for (int i = start; i < start + blockSize && i < n; ++i) {
if (vec[i] == id) {
return i;
}
}
// 如果在块内未找到目标元素,则返回-1
return -1;
}