代码如下:
#include <iostream>
using namespace std;
void selectionSort(int arr[], int n)
{
for(int i = 0; i < n; i ++)
{
//
int minIndex = i;
for(int j = i + 1; j < n; j ++)
if(arr[j]<arr[minIndex])
minIndex = j;
swap(arr[i], arr[minIndex]);
}
}
算法实现的是:在剩余的元素中找最小的数放在当前的位置, 算法复杂度为
交换数组中的两个元素:
swap(arr[i], arr[minIndex]);
使用模板函数定义排序数组:
#include <iostream>
using namespace std;
template<typename T>
void selectionSort(T arr[], int n)
{
for(int i = 0; i < n; i ++)
{
//
int minIndex = i;
for(int j = i + 1; j < n; j ++)
if(arr[j]<arr[minIndex])
minIndex = j;
swap(arr[i], arr[minIndex]);
}
}
定义模板类型:
template<typename T>
这样排序算法就可以排序:int, float, string, 以及自己定义的格式