插入排序(Insertion Sort)的基本思想是:每次将一个待排序的记录,按其关键字大小插入到前面已经排好序的子文件中的适当位置,直到全部记录插入完成为止。
#ifndef INSERTSORT_H
#define INSERTSORT_H
template<class T> void InsertSort(T *a,int len) //直插排序算法
{
T temp;
int j;
for(int i = 1;i < len;++i)
{
if(a[i] < a[i - 1])
{
temp = a[i]; //记录较小的值
for(j = i - 1;j >= 0 && a[j] > temp;--j)
a[j + 1] = a[j]; //将值向后移
a[j + 1] = temp; //将较小的值插入正确位置
}
}
}
#endif //INSERTSORT_H
#include "InsertSort.h"
#include <stdio.h>
int main()
{
int a[] = {13,10,11,34,23,17,29,31};
InsertSort(a,sizeof(a)/sizeof(*a));
for(int i = 0;i < sizeof(a) / sizeof(*a);++i)
printf("%d ",a[i]);
printf("\n");
return 0;
}