交换排序之 冒泡排序(优化) (稳定)

本文介绍了冒泡排序的基本原理及其三种不同实现方式,包括原始版本、部分优化版本和完全优化版本。详细展示了每种方法的代码实现,并分析了它们的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
using namespace std;


//冒泡排序属于交换排序 
//空间复杂度 O(1)
//时间复杂度最坏是O(n2)
//          最好是O(n)
//          平均数O(n2)
template<class T>
void BubbleSort(T array[],int n)//版本1
{
	for(int i=0;i<n-1;++i)
	{
		for(int j=0;i<n-1-i;++j)
		{
			if(array[j]>array[j+1])
			{
				std::swap(array[j],array[j+1]);
			}
		}
	}
}
template<class T>
void BubbleSort(T array[],int n )//优化版本2
{
	 int Count=n-1;
	 while(Count)
	 {
		 int pos=0;
		 for(int j=0;j<Count;++j)
		 {
			 if(array[j]>array[j+1])//。由于pos位置之后的记录均已交换到位,故在进行下一趟排序时只要扫描到pos位置即可。
			 {
                 pos=j;
				 std::swap(array[j],array[j+1]);
			 }
		 }
		 Count=pos;
	 }
}

template<class T>
void BubbleSort(T array[],int n )//优化版本3
{
	int low =0;
	int high=n-1;
	while(low <high) //自己不和自己交换所以没有等于
	{
		for(int i=low;i<high;++i)
		{
			if(array[i]>array[i+1])
			{
				std::swap(array[i],array[i+1]);
			}
		}
		--high;//选出了一个最大的
		for(i=high;i>low;--i)
		{
			if(array[i]<array[i-1])
			{
				std::swap(array[i],array[i-1]);
			}
		}
		++low;//选出了最小的
	}
}
int main()
{

int a[]={9,7,8,6,5,4,3,2,1};
BubbleSort<int> (a,sizeof(a)/sizeof(*a));
for(int *p=&a[0];p<&a[0]+sizeof(a)/sizeof(*a);++p)
{
	cout<<*p<<" ";
}
cout<<endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值