C++排序

1、插入排序

思想:后面的数和第一个数比较大小进行排序,排序好再后面的数与前两个数进行比较排序,类推……

模板:

template<class T>
void InsertionSort(T A[],int n)
{
	int i,j;
	T temp;
	for(i=1;i<n;i++)
	{
		j=i;
		temp=A[i];
		while(j>&&temp<A[j-1])
		{
			A[j]=A[j-1];
			j--;
		}
		A[j]=temp;
	}
}

2、选择排序

思想:将第一个数和后面的每个数进行比较,如果后面的比前面小,就两个数调换位置,最后就将最小的数放在最前面。

template<class T>
void Swap(T& x,T& y)
{
	T temp;
	temp=x;
	x=y;
	y=temp;
}
template<class T>
void SelectionSort(T A[],int n)
{
	int smallIndex;
	int i,j;
	for(i=0,i<n-1;i++)
	{
		smallIndex=i;
		for(j=i+1;j<n;j++)
			if(A[j]<A[smallIndex])
				samllIndex=j;
			Swap(A[i],A[smallIndex]);
	}
}

3、冒泡排序

思想:从第一个数开始,往下每两个数进行比较,如果后面闭前面小,就调换位置,这样一趟下来就将最大的放到最后。(速度比选择排序要快)

template<class T>
void Swap(T& x,T& y)
{
	T temp;
	temp=x;
	x=y;
	y=temp;
}
template<class T>
void BubbleSort(T A[],int n)
{
	int i,j;
	int lastExchangeIndex;
	i=n-1;
	while(i>0)
	{
		lastExchangeIndex=0;
		for(j=0;j<i;j++)
			if(A[j+1]<A[j])
			{
				Swap(A[j],A[j+1]);
				lastExchangeIndex=j;
			}
			i=lastExchangeIndex
	}
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值