代碼如下:
#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, 以及自己定義的格式