编写一个选择排序的函数模板并在main函数中测试
时间: 2023-06-16 07:03:06 浏览: 50
下面是使用模板编写的选择排序函数:
```cpp
template<typename T>
void selectionSort(T arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
swap(arr[i], arr[minIndex]);
}
}
}
```
使用示例:
```cpp
#include <iostream>
using namespace std;
template<typename T>
void selectionSort(T arr[], int n);
int main() {
int arr1[] = {4, 2, 8, 5, 1, 9, 6};
double arr2[] = {3.4, 1.2, 2.8, 0.5, 6.7};
selectionSort(arr1, 7);
selectionSort(arr2, 5);
for (int i = 0; i < 7; i++) {
cout << arr1[i] << " ";
}
cout << endl;
for (int i = 0; i < 5; i++) {
cout << arr2[i] << " ";
}
cout << endl;
return 0;
}
template<typename T>
void selectionSort(T arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
swap(arr[i], arr[minIndex]);
}
}
}
```
输出结果:
```
1 2 4 5 6 8 9
0.5 1.2 2.8 3.4 6.7
```