用C++代码创建表并实现顺序查找和折半查找的实验步骤
时间: 2024-05-01 12:23:36 浏览: 114
实验步骤如下:
1. 定义结构体表示表中的元素,包括关键字和其他属性(如果有的话)。
```c++
struct Element {
int key;
// other properties
};
```
2. 创建表,可以使用数组或者链表等数据结构,这里使用数组实现,定义一个指针变量作为数组的首地址,以及一个整型变量表示表的长度。
```c++
Element* table = nullptr;
int length = 0;
```
3. 定义顺序查找函数,按照关键字从头到尾顺序查找表中的元素,返回元素在表中的位置,如果找不到则返回-1。
```c++
int sequentialSearch(int key) {
for (int i = 0; i < length; ++i) {
if (table[i].key == key) {
return i;
}
}
return -1;
}
```
4. 定义折半查找函数,先对表中的元素按照关键字排序,然后按照二分法查找元素,返回元素在表中的位置,如果找不到则返回-1。
```c++
int binarySearch(int key) {
// sort elements by key
// ...
int left = 0;
int right = length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (table[mid].key == key) {
return mid;
}
if (table[mid].key < key) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
```
5. 在main函数中初始化表,调用顺序查找和折半查找函数进行测试。
```c++
int main() {
// initialize table
// ...
int key = 42;
int pos = sequentialSearch(key);
if (pos != -1) {
cout << "Found at position " << pos << endl;
} else {
cout << "Not found." << endl;
}
pos = binarySearch(key);
if (pos != -1) {
cout << "Found at position " << pos << endl;
} else {
cout << "Not found." << endl;
}
return 0;
}
```
阅读全文
相关推荐

















