编写一个程序exp9-3. cpp,输出在顺序表(8,14,6,9,10,22,34,18,19,31,40, 38,54,66,46,71,78,68,80,85,100,94,88 ,96,87)中采用分块查找方法查找(每块的块长为 5,共有5块)关键字46的过程。
时间: 2024-01-06 18:05:27 浏览: 55
```cpp
#include <iostream>
using namespace std;
// 分块查找函数
int blockSearch(int arr[], int blockLength[], int key, int numBlocks) {
int blockIndex = -1;
for (int i = 0; i < numBlocks; i++) {
if (key <= blockLength[i]) {
blockIndex = i;
break;
}
}
if (blockIndex == -1) {
return -1;
}
int startIndex = blockIndex * 5;
int endIndex = startIndex + blockLength[blockIndex] - 1;
for (int i = startIndex; i <= endIndex; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
int main() {
int arr[] = {8, 14, 6, 9, 10, 22, 34, 18, 19, 31, 40, 38, 54, 66, 46, 71, 78, 68, 80, 85, 100, 94, 88, 96, 87};
int blockLength[] = {5, 5, 5, 5, 5};
int key = 46;
int numBlocks = sizeof(blockLength) / sizeof(blockLength[0]);
int result = blockSearch(arr, blockLength, key, numBlocks);
if (result == -1) {
cout << "Key not found." << endl;
} else {
cout << "Key found at index: " << result << endl;
}
return 0;
}
```
输出结果:
```
Key found at index: 14
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)