使用c++语言分别实现基数排序和归并排序,输入任意10个数后,能从大到小排序输出
时间: 2024-12-10 15:34:47 浏览: 10
实验七:内部排序指导书.pdf
基数排序是一种非比较整数排序算法,它通过将整数按照位数切割成不同的数字,然后对每个位数分别进行排序,最后再组合起来得到有序序列。以下是基数排序的一个简单C++实现:
```cpp
#include <iostream>
#include <vector>
using namespace std;
void countingSort(vector<int>& arr, int exp) {
vector<int> output(arr.size());
vector<int> count(10, 0);
for (int i = 0; i < arr.size(); i++) {
count[(arr[i] / exp) % 10]++;
}
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
for (int i = arr.size() - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}
for (int i = 0; i < arr.size(); i++) {
arr[i] = output[i];
}
}
void radixsort(vector<int>& arr) {
int max_val = *max_element(arr.begin(), arr.end());
for (int exp = 1; max_val / exp > 0; exp *= 10) {
countingSort(arr, exp);
}
}
int main() {
vector<int> numbers = {97, 15, 86, 24, 67, 56, 32, 78, 43, 10};
radixsort(numbers);
cout << "Sorted array in descending order:\n";
for (auto num : numbers) {
cout << num << " ";
}
cout << "\n";
return 0;
}
```
归并排序是一种分治策略的排序算法,将数组不断二分,直到每个子数组只有一个元素,然后再合并。以下是归并排序的C++实现:
```cpp
#include <iostream>
#include <vector>
void merge(vector<int>& arr, int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
vector<int> L(n1), R(n2);
for (int i = 0; i < n1; i++)
L[i] = arr[l + i];
for (int j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
if (L[i] >= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(vector<int>& arr, int l, int r) {
if (l < r) {
int m = l+(r-l)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
int main() {
vector<int> numbers = {97, 15, 86, 24, 67, 56, 32, 78, 43, 10};
mergeSort(numbers, 0, numbers.size() - 1);
cout << "Sorted array in descending order:\n";
for (auto num : numbers) {
cout << num << " ";
}
cout << "\n";
return 0;
}
```
上述代码首先实现了基数排序和归并排序,然后在主函数中使用这两个排序算法对给定的10个数进行降序排序,并打印结果。
阅读全文