顺序查找和折半查找c++代码
时间: 2023-11-04 15:16:40 浏览: 127
顺序查找(线性查找)C++代码:
```cpp
#include <iostream>
using namespace std;
int linearSearch(int arr[], int n, int x) {
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
return i;
}
}
return -1;
}
int main() {
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = linearSearch(arr, n, x);
if (result == -1) {
cout << "Element not found" << endl;
} else {
cout << "Element found at index " << result << endl;
}
return 0;
}
```
折半查找(二分查找)C++代码:
```cpp
#include <iostream>
using namespace std;
int binarySearch(int arr[], int l, int r, int x) {
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == x) {
return mid;
}
if (arr[mid] < x) {
l = mid + 1;
} else {
r = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
if (result == -1) {
cout << "Element not found" << endl;
} else {
cout << "Element found at index " << result << endl;
}
return 0;
}
```
阅读全文