直接插入排序算法

插入排序(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;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值