排序算法之冒泡排序

来源:互联网 发布:网络防火墙作用 编辑:程序博客网 时间:2024/06/12 23:26
冒泡排序算法(Bubble Sort)
比较相邻的元素。如果第一个比第二个大,就交换他们两个。
2 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
3 针对所有的元素重复以上的步骤,除了最后一个。
4 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较    
代码:
#include<iostream>
#define LEN 9
using namespace std;
int main( )
{
int ARRAY[LEN]={5,6,8,2,4,1,9,3,7};
cout<<"Before sorted:"<<endl;
for (int i=0; i<LEN; i++)
{
cout<<ARRAY[i]<<"  ";
}
cout<<endl;


int temp;
for(int j=0;j<LEN-1;j++)
{
for(int i=0;i<LEN-1-j;i++)
{
if(ARRAY[i]>ARRAY[i+1])
{
temp=ARRAY[i];
ARRAY[i]=ARRAY[i+1];
ARRAY[i+1]=temp;
}
}
cout<<"After the "<<j+1<<" st turn"<<endl;
for (int n=0; n<LEN; n++)
{
cout<<ARRAY[n]<<"  ";
}
cout<<endl;
cout<<endl;
}
cout<<"After sorted"<<endl;
for(int i=0; i<LEN; i++)
{
cout<<ARRAY[i]<<"  ";
}
cout<<endl;
return 0;
}


0 0