编写一个名为chazhao.cpp的程序代码。 实现以下功能: (1)创建个含有10个元素的有序序列。 (2)顺序查找(有哨兵位)。 (3)递归折半查找 (4)非递归折半查找。 要求以上功能写成函数段,只写个主函数调用以上功能来验证函数。
时间: 2024-12-30 16:36:37 浏览: 6
```cpp
#include <iostream>
using namespace std;
// 有序序列(哨兵位)
struct SentinelList {
int data;
SentinelList* next;
};
SentinelList* create_sorted_list(int size) {
SentinelList* head = new SentinelList{0, nullptr}; // 创建哨兵节点
for (int i = 1; i <= size; ++i) {
SentinelList* newNode = new SentinelList{i, head->next};
head->next = newNode;
}
return head;
}
// 顺序查找(有哨兵位)
bool sequential_search(SentinelList* list, int target) {
SentinelList* current = list;
while (current != nullptr && current->data != target) {
current = current->next;
}
if (current == nullptr) {
return false;
} else {
return true;
}
}
// 递归折半查找
bool recursive_binary_search(SentinelList* list, int target, SentinelList* start = nullptr) {
if (start == nullptr) {
start = list;
}
if (start->data == target) {
return true;
} else if (start->data > target || (start->next == nullptr && start->data < target)) {
return false;
}
SentinelList* mid = get_middle(start);
return recursive_binary_search(mid->next, target, mid);
}
// 非递归折半查找
SentinelList* get_middle(SentinelList* list) {
SentinelList* slow = list, *fast = list;
while (fast->next != nullptr && fast->next->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
// 非递归折半查找
bool non_recursive_binary_search(SentinelList* list, int target) {
return binary_search(list, target, get_middle(list));
}
// 公共部分:二分查找辅助函数
bool binary_search(SentinelList* start, int target, SentinelList* middle) {
if (middle == nullptr) {
return sequential_search(start, target);
}
if (target < middle->data) {
return binary_search(start, target, middle->next);
} else {
return binary_search(middle->next, target, nullptr);
}
}
int main() {
int size = 10;
SentinelList* list = create_sorted_list(size);
cout << "Sequential Search (Target: 5): " << (sequential_search(list, 5) ? "Found" : "Not Found") << endl;
cout << "Recursive Binary Search (Target: 5): " << (recursive_binary_search(list, 5) ? "Found" : "Not Found") << endl;
cout << "Non-Recursive Binary Search (Target: 5): " << (non_recursive_binary_search(list, 5) ? "Found" : "Not Found") << endl;
delete list; // 清理内存
return 0;
}
```
这个`chazhao.cpp`程序实现了四个功能:创建有序列表、顺序查找、递归折半查找和非递归折半查找。在`main`函数中对每个功能进行了测试。注意,在实际应用中,需要确保正确的内存管理。
阅读全文