选择排序就是每次选择最小的放最前面,一圈下来就有序了。
选择排序模板编程
#include<iostream>
using namespace std;
template<typename T>
void selectSort(T a[], int n)
{
if (n <= 1)//当数组元素个数小于2时,不需要排序。
return;
T temp;
for (int i = 0; i < n - 1; i++)
{
int minID = i;
for (int j = i + 1; j < n; j++)
{
if (a[j] < a[minID])
minID = j;
}
temp = a[i];
a[i] = a[minID];
a[minID] = temp;
}
}
int main()
{
const int n = 5;
float a[n] = { 3.2,-5.35,2.65,1.89,0.67 };
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
selectSort(a, n);
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
运行结果: