分别用顺序查找法和折半查找法实现对给定值得查找。
时间: 2023-07-18 10:21:56 浏览: 113
顺序查找和折半查找
顺序查找法的实现如下:
```cpp
#include <iostream>
using namespace std;
int seq_search(int arr[], int len, int key) {
for (int i = 0; i < len; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
int main() {
int arr[] = {1, 3, 5, 7, 9, 11};
int len = sizeof(arr) / sizeof(arr[0]);
int key = 7;
int pos = seq_search(arr, len, key);
if (pos != -1) {
cout << "顺序查找成功,元素 " << key << " 在数组中的下标为 " << pos << endl;
} else {
cout << "顺序查找失败,元素 " << key << " 不在数组中" << endl;
}
return 0;
}
```
折半查找法的实现如下:
```cpp
#include <iostream>
using namespace std;
int binary_search(int arr[], int len, int key) {
int left = 0, right = len - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {1, 3, 5, 7, 9, 11};
int len = sizeof(arr) / sizeof(arr[0]);
int key = 7;
int pos = binary_search(arr, len, key);
if (pos != -1) {
cout << "折半查找成功,元素 " << key << " 在数组中的下标为 " << pos << endl;
} else {
cout << "折半查找失败,元素 " << key << " 不在数组中" << endl;
}
return 0;
}
```
阅读全文