如何在C++中实现折半查找(二分查找)和顺序查找算法,并包括它们之间的查找效率对比示例,以及如何添加清屏和退出程序的功能?
时间: 2025-06-09 21:02:15 浏览: 10
在C++中,你可以分别通过以下方式实现折半查找(二分查找)和顺序查找算法:
**顺序查找(Sequential Search)**
顺序查找是一种简单的线性搜索,它从数组的第一个元素开始逐个比较,直到找到目标值或遍历完整个数组。
```cpp
#include <iostream>
void sequential_search(int arr[], int target, int n) {
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
std::cout << "Target found at index: " << i << std::endl;
break;
}
}
else {
std::cout << "Element not found." << std::endl;
}
}
```
**折半查找(Binary Search)**
折半查找适用于已经排序的数组。它首先将数组分为两部分,然后比较中间元素与目标值,如果相等则返回索引,如果目标值小于中间值,则在左半部分继续查找,反之在右半部分。
```cpp
void binary_search(int arr[], int target, int low, int high) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
std::cout << "Target found at index: " << mid << std::endl;
return;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
std::cout << "Element not found." << std::endl;
}
```
关于效率对比,折半查找的时间复杂度是O(log n),对于大规模数据来说,比顺序查找的平均时间复杂度O(n)更高效。但在最坏情况下,例如目标值不在数组内,两者都退化为O(n)。
添加清屏和退出程序功能可以借助一些库函数如`system("cls")`(Windows系统)或`clear()`(Linux/Mac系统),以及标准输入流`std::cin.get()`来等待用户按键。然而,在实际项目中,这些操作通常不会直接嵌入到查找函数中,而是作为控制台应用的一部分独立处理。
```cpp
#include <cstdlib> // 对于system函数
#include <conio.h> // 对于getch函数(Windows)
// 添加清屏
void clear_screen() {
#ifdef _WIN32
system("cls");
#else
std::cout << "\033[2J\033[H"; // Linux/macOS清除屏幕
#endif
}
// 退出程序并清屏
void exit_and_clear() {
clear_screen();
getchar(); // 等待按键
exit(0);
}
```
阅读全文
相关推荐



















