插入排序就是往有序队列里一个一个的插入数组元素。
插入排序模板编程
#include<iostream>
using namespace std;
template<typename T>
void insertSort(T a[], int n)
{
if (n <= 1)//当数组元素个数小于2时,不需要排序。
return;
T temp;
for (int i = 1; i < n; i++)
{
for (int j = i - 1; j >= 0; j--)
{
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
else
break;
}
}
}
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;
insertSort(a, n);
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
运行结果: