C++实现:1.给定无序序列{1,3,4,34,67,8,13,25,39,23,10,41,55,66,52,21,64,76,68,789,546,23,56,90,109,143,178,967,11,19}; 2.查找与输入的给定关键字相同的元素,使用指定的算法进行查找,若存在则输出找到的元素在序列中的位序(第一个数位序记为1)和需要进行的比较次数,不存在则输出"No",序列位序从1到n。 3.实现顺序查找和折半查找算法。
时间: 2023-12-12 19:02:38 浏览: 68
C++数值的查找.ppt
顺序查找算法的实现:
```cpp
#include <iostream>
using namespace std;
int sequentialSearch(int arr[], int n, int key, int& count) {
for (int i = 0; i < n; i++) {
count++;
if (arr[i] == key) {
return i + 1; // 返回位序,从1开始
}
}
return -1; // 找不到返回-1
}
int main() {
int arr[] = {1, 3, 4, 34, 67, 8, 13, 25, 39, 23, 10, 41, 55, 66, 52, 21, 64, 76, 68, 789, 546, 23, 56, 90, 109, 143, 178, 967, 11, 19};
int n = sizeof(arr) / sizeof(arr[0]);
int key, count = 0;
cout << "请输入要查找的关键字:" << endl;
cin >> key;
int pos = sequentialSearch(arr, n, key, count);
if (pos == -1) {
cout << "No" << endl;
} else {
cout << "位序:" << pos << endl;
cout << "比较次数:" << count << endl;
}
return 0;
}
```
折半查找算法的实现:
```cpp
#include <iostream>
using namespace std;
int binarySearch(int arr[], int l, int r, int key, int& count) {
while (l <= r) {
count++;
int mid = l + (r - l) / 2;
if (arr[mid] == key) {
return mid + 1; // 返回位序,从1开始
}
if (arr[mid] < key) {
l = mid + 1;
} else {
r = mid - 1;
}
}
return -1; // 找不到返回-1
}
int main() {
int arr[] = {1, 3, 4, 34, 67, 8, 13, 25, 39, 23, 10, 41, 55, 66, 52, 21, 64, 76, 68, 789, 546, 23, 56, 90, 109, 143, 178, 967, 11, 19};
int n = sizeof(arr) / sizeof(arr[0]);
int key, count = 0;
cout << "请输入要查找的关键字:" << endl;
cin >> key;
int pos = binarySearch(arr, 0, n - 1, key, count);
if (pos == -1) {
cout << "No" << endl;
} else {
cout << "位序:" << pos << endl;
cout << "比较次数:" << count << endl;
}
return 0;
}
```
阅读全文