c++弄出随机10个数用选择法对10个整数从大到小排列
时间: 2024-09-26 10:07:59 浏览: 26
在C++中,你可以使用标准库`<cstdlib>`和`<ctime>`来生成随机数,并结合排序算法(如快速选择、堆排序等)对10个整数进行降序排列。这里是一个简单的示例,使用了快速选择作为简化版的排序,因为快速选择对于大型数据集效率较高:
```cpp
#include <iostream>
#include <vector>
#include <cstdlib> // for rand and srand
#include <ctime> // for time
// 随机数生成函数
int random_number(int min, int max) {
return min + static_cast<int>((max - min + 1) * std::rand() / RAND_MAX);
}
// 使用快速选择法选择最大值
int find_max(std::vector<int>& arr, size_t low, size_t high) {
if (low == high) { // base case: only one element
return arr[low];
}
size_t pivot_index = partition(arr, low, high); // partition the array
if (pivot_index == high - 1) { // pivot is already at its final place
return arr[pivot_index];
} else if (pivot_index < high - 1) {
return find_max(arr, pivot_index + 1, high); // recur on right partition
} else {
return find_max(arr, low, pivot_index); // recur on left partition
}
}
// Partition function for quickselect
size_t partition(std::vector<int>& arr, size_t low, size_t high) {
int pivot = arr[high]; // take last element as pivot
size_t i = low - 1;
for (size_t j = low; j < high; ++j) {
if (arr[j] >= pivot) {
i++;
std::swap(arr[i], arr[j]);
}
}
std::swap(arr[i + 1], arr[high]); // put pivot in its correct position
return i + 1;
}
int main() {
std::srand(std::time(0)); // seed the random number generator
std::vector<int> numbers(10);
for (auto& num : numbers) {
num = random_number(1, 100); // generate a random integer between 1 and 100
}
int max_num = find_max(numbers, 0, numbers.size() - 1);
std::cout << "Sorted numbers (in descending order): ";
for (const auto& num : numbers) {
std::cout << num << " ";
}
std::cout << "\nMax number: " << max_num << std::endl;
return 0;
}
```
阅读全文