编写一个名为chazhao.cpp的程序代码。 实现以下功能: (1)创建一个含有10个元素的有序序列。 (2)顺序查找(有哨兵位)。 (3)递归折半查找。 (4)非递归折半查找。 要求以上功能写成函数段,只写一个主函数调用以上功能来验证函数。
时间: 2024-12-30 13:38:20 浏览: 7
以下是一个简单的`chazhao.cpp`程序代码片段,它实现了你所描述的功能。这个程序假设我们使用一个自定义的`Node`结构体作为数组,并包含哨兵位在第一个元素之前。这里使用了C++来编写:
```cpp
#include <iostream>
#include <vector>
// 定义一个节点结构体
struct Node {
int value;
Node* next;
};
// 创建有序序列(含哨兵位)
Node* create_sorted_sequence(int size) {
Node* head = new Node{0}; // 哨兵位置
for (int i = 1; i <= size; ++i) {
Node* newNode = new Node{i};
newNode->next = head->next;
head->next = newNode;
}
return head->next;
}
// 顺序查找
bool linear_search(Node* head, int target) {
Node* current = head;
while (current != nullptr && current->value != target) {
current = current->next;
}
return current != nullptr;
}
// 递归折半查找
bool recursive_binary_search(Node* head, int target, Node* start = nullptr) {
if (start == nullptr) start = head;
Node* mid = start->next ? start->next : start;
if (mid->value == target) return true;
else if (mid->value > target)
return recursive_binary_search(head, target, start);
else
return recursive_binary_search(head, target, mid->next);
}
// 非递归折半查找
bool non_recursive_binary_search(Node* head, int target) {
Node* start = head->next;
while (start != nullptr) {
Node* mid = start + (start - head) / 2;
if (mid->value == target) return true;
else if (mid->value > target)
start = mid->next;
else
start = mid;
}
return false;
}
// 主函数
int main() {
const int sequence_size = 10;
Node* sequence = create_sorted_sequence(sequence_size);
std::cout << "Searching for element using different methods:\n";
int search_target;
std::cout << "Enter a number to search for: ";
std::cin >> search_target;
// 测试顺序查找
bool found_seq = linear_search(sequence, search_target);
std::cout << "Linear search result: " << (found_seq ? "Found" : "Not Found") << "\n";
// 测试递归折半查找
bool found_rec_bin = recursive_binary_search(sequence, search_target);
std::cout << "Recursive binary search result: " << (found_rec_bin ? "Found" : "Not Found") << "\n";
// 测试非递归折半查找
bool found_non_rec_bin = non_recursive_binary_search(sequence, search_target);
std::cout << "Non-recursive binary search result: " << (found_non_rec_bin ? "Found" : "Not Found") << "\n";
delete sequence; // 释放内存
return 0;
}
```
阅读全文