线性表的图书顺序查找和折半查找c++
时间: 2024-06-13 17:09:44 浏览: 121
以下是C++实现线性表的顺序查找和折半查找的示例代码:
1. 顺序查找
```cpp
#include <iostream>
using namespace std;
const int MAXSIZE = 100;
typedef struct {
int key;
// 其他数据项
} ElemType;
typedef struct {
ElemType elem[MAXSIZE + 1];
int length;
} SSTable;
int Search_Seq(SSTable ST, int key) {
ST.elem[0].key = key;
int i = ST.length;
while (ST.elem[i].key != key) {
i--;
}
return i;
}
int main() {
SSTable ST;
ST.length = 5;
ST.elem[1].key = 1;
ST.elem[2].key = 3;
ST.elem[3].key = 5;
ST.elem[4].key = 7;
ST.elem[5].key = 9;
int index = Search_Seq(ST, 5);
if (index == 0) {
cout << "未找到" << endl;
} else {
cout << "找到,下标为:" << index << endl;
}
return 0;
}
```
2. 折半查找
```cpp
#include <iostream>
using namespace std;
const int MAXSIZE = 100;
typedef struct {
int key;
// 其他数据项
} ElemType;
typedef struct {
ElemType elem[MAXSIZE + 1];
int length;
} SSTable;
int Search_Bin(SSTable ST, int key) {
int low = 1, high = ST.length;
while (low <= high) {
int mid = (low + high) / 2;
if (ST.elem[mid].key == key) {
return mid;
} else if (ST.elem[mid].key > key) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return 0;
}
int main() {
SSTable ST;
ST.length = 5;
ST.elem[1].key = 1;
ST.elem[2].key = 3;
ST.elem[3].key = 5;
ST.elem[4].key = 7;
ST.elem[5].key = 9;
int index = Search_Bin(ST, 5);
if (index == 0) {
cout << "未找到" << endl;
} else {
cout << "找到,下标为:" << index << endl;
}
return 0;
}
```
阅读全文