冒泡排序算法C++实现

//源代码如下,好久没写算法代码了,最近考软件设计师,复习了下

#include<iostream>
#include<iomanip>
using namespace std;
template <class Type>
void bubbsort(Type a[],int n)
{
	int i,j;
	for(i=1;i<=n-1;i++)
		for(j=0;j<=n-i-1;j++)
		{
			if(a[j]>a[j+1])
			{	Type temp=a[j];
			    a[j]=a[j+1];
				a[j+1]=temp;
			}
		}
}
void main(){
	int a[]={3,2,40,155,110,12,80,1};
	cout<<"排序前的数组为:"<<endl;
	for(int i=0;i<8;i++)
		cout<<a[i]<<setw(6);
	cout<<endl;
	bubbsort(a,8);
	cout<<"排序后的数组为:"<<endl;
		for(int j=0;j<8;j++)
		cout<<a[j]<<setw(6);
		cout<<endl;
}
 

 

总结:

1.setw(length)函数的使用,include<iomanip>.

2.template <class Type>声明后,Type的使用.

3.记得BUBBSORT中的for(int i=1;i<n-1;i++)//because n 个元素排序,要比较n-1次就完整了

                               for(int j=0;j<n-i;j++)//a[j]为比较的元素值,后面有a[j+1],故到n-i-1的j下标就行了。

4.记得main中实例a数组的大小和下标,for输出和调用bubbsort时size的设置。

 

你可能感兴趣的:(冒泡排序)