同时实现顺序查找和折半查找完整代码c++
时间: 2024-05-12 16:13:10 浏览: 88
顺序查找代码:
```c++
#include <iostream>
using namespace std;
int sequentialSearch(int arr[], int n, int key) {
for(int i=0; i<n; i++) {
if(arr[i] == key) {
return i;
}
}
return -1;
}
int main() {
int arr[] = {10, 7, 23, 98, 5, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 98;
int index = sequentialSearch(arr, n, key);
if(index == -1) {
cout << "Element not found" << endl;
}
else {
cout << "Element found at index: " << index << endl;
}
return 0;
}
```
折半查找代码:
```c++
#include <iostream>
using namespace std;
int binarySearch(int arr[], int n, int key) {
int low = 0, high = n-1;
while(low <= high) {
int mid = (low + high) / 2;
if(arr[mid] == key) {
return mid;
}
else if(arr[mid] < key) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {5, 7, 10, 15, 23, 98};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 98;
int index = binarySearch(arr, n, key);
if(index == -1) {
cout << "Element not found" << endl;
}
else {
cout << "Element found at index: " << index << endl;
}
return 0;
}
```
阅读全文