请用C++写一个顺序查找和折半查找,要求数据通过键盘输入,并显示注释
时间: 2024-02-07 13:03:01 浏览: 67
顺序查找(线性查找):
```c++
#include <iostream>
using namespace std;
int seqSearch(int arr[], int n, int x) {
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
return i;
}
}
return -1;
}
int main() {
int n, x;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "Enter the element to search: ";
cin >> x;
int index = seqSearch(arr, n, x);
if (index != -1) {
cout << x << " found at index " << index << endl;
} else {
cout << x << " not found" << endl;
}
return 0;
}
```
折半查找(二分查找):
```c++
#include <iostream>
using namespace std;
int binarySearch(int arr[], int n, int x) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] > x) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
int main() {
int n, x;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array (in ascending order): ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "Enter the element to search: ";
cin >> x;
int index = binarySearch(arr, n, x);
if (index != -1) {
cout << x << " found at index " << index << endl;
} else {
cout << x << " not found" << endl;
}
return 0;
}
```
注:顺序查找适用于小规模数据,而折半查找适用于大规模有序数据。
阅读全文