键盘上任意顺序输入15个整型数据,将数组元素按降序排列。再读入一个整数m ,使用折半查找方法,查找m是否在数组中。若在,输出其位置;若不在,输出“no"。
时间: 2024-12-12 09:21:47 浏览: 66
要完成这个任务,可以使用C++编写一个程序,首先接收15个整数并将它们放入数组,然后对数组进行降序排序,最后使用折半查找算法找到指定值的位置。以下是完整的代码实现:
```cpp
#include <iostream>
#include <vector>
using namespace std;
// 升序比较函数,用于sort函数
bool compare(int a, int b) {
return a > b;
}
void insertAndSort(vector<int>& arr, int n) {
for (int i = 0; i < n; ++i) {
int num;
cin >> num;
arr.push_back(num);
}
sort(arr.begin(), arr.end(), compare); // 对数组进行降序排序
}
int binarySearch(vector<int>& arr, int target, int low, int high) {
if (low > high)
return -1;
int mid = low + (high - low) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] > target)
return binarySearch(arr, target, low, mid - 1);
else
return binarySearch(arr, target, mid + 1, high);
}
int main() {
vector<int> arr(15);
insertAndSort(arr, 15);
int m;
cout << "Enter the value to search: ";
cin >> m;
int result = binarySearch(arr, m, 0, arr.size() - 1);
if (result != -1)
cout << "Value found at position " << result + 1 << endl;
else
cout << "no" << endl;
return 0;
}
```
在这个程序中,我们先创建了一个大小为15的整数向量`arr`,然后通过循环接收用户的输入并插入到数组中。接着,我们使用`compare`函数作为`sort`的第三个参数,使得数组按照降序排列。然后,用户输入一个值`m`,我们调用`binarySearch`函数进行查找,如果找到了则输出位置,否则输出"No"。
阅读全文
相关推荐










