设计一个实现排序功能的函数模板,排序算法任意。要求排序结果由小到大,并在预设代码中验证int型数组和char型数组的排序结果
时间: 2024-05-05 16:16:29 浏览: 50
使用函数模板进行排序
```c++
#include <iostream>
using namespace std;
template <typename T>
void bubbleSort(T arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j+1]) {
swap(arr[j], arr[j+1]);
}
}
}
}
int main() {
int a[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
char b[] = {'c', 'b', 'a', 'e', 'd'};
int n = sizeof(a) / sizeof(a[0]);
bubbleSort(a, n);
cout << "Sorted int array: ";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
n = sizeof(b) / sizeof(b[0]);
bubbleSort(b, n);
cout << "Sorted char array: ";
for (int i = 0; i < n; i++) {
cout << b[i] << " ";
}
cout << endl;
return 0;
}
```
阅读全文