用c++使用函数模板实现任意类型的数组的降序排序。
时间: 2024-02-13 18:02:38 浏览: 76
用C++实现各种排序算法
好的,可以参考下面的代码实现:
```c++
#include <iostream>
using namespace std;
template <typename T>
void selectionSort(T arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int maxIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] > arr[maxIndex]) {
maxIndex = j;
}
}
swap(arr[i], arr[maxIndex]);
}
}
int main() {
int intArr[] = { 3, 6, 1, 9, 2 };
double doubleArr[] = { 3.5, 6.8, 1.2, 9.6, 2.7 };
char charArr[] = { 'c', 'b', 'a', 'e', 'd' };
int n = 5;
cout << "Original int array: ";
for (int i = 0; i < n; i++) {
cout << intArr[i] << " ";
}
selectionSort(intArr, n);
cout << "\nSorted int array: ";
for (int i = 0; i < n; i++) {
cout << intArr[i] << " ";
}
cout << "\nOriginal double array: ";
for (int i = 0; i < n; i++) {
cout << doubleArr[i] << " ";
}
selectionSort(doubleArr, n);
cout << "\nSorted double array: ";
for (int i = 0; i < n; i++) {
cout << doubleArr[i] << " ";
}
cout << "\nOriginal char array: ";
for (int i = 0; i < n; i++) {
cout << charArr[i] << " ";
}
selectionSort(charArr, n);
cout << "\nSorted char array: ";
for (int i = 0; i < n; i++) {
cout << charArr[i] << " ";
}
return 0;
}
```
这里定义了一个函数模板 `selectionSort`,可以对任意类型的数组进行降序排序。在主函数中,我们分别定义了整型、双精度浮点型和字符型数组,并通过函数模板 `selectionSort` 对它们进行排序。
阅读全文