用c++ 编写一个选择排序的函数模板。
时间: 2024-02-18 19:35:11 浏览: 23
以下是选择排序的函数模板实现:
```c++
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
void selectionSort(vector<T>& arr) {
int n = arr.size();
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]);
}
}
}
int main() {
vector<int> arr = {64, 25, 12, 22, 11};
selectionSort(arr);
for (auto elem : arr) {
cout << elem << " ";
}
cout << endl;
return 0;
}
```
这里我们使用了模板类型 `T`,使得函数可以用于不同类型的数组排序。函数通过遍历数组找到当前未排序部分中的最小元素,并将其交换到已排序部分的末尾。时间复杂度为 $O(n^2)$。