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

#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;
}

你可能感兴趣的:(交换排序之 冒泡排序(优化) (稳定))