冒泡排序
对于N个整数(数据由键盘输入)进行升序排列。
冒泡排序将相邻元素进行比较,比较大小后进行换位置,n各元素比较n-1次,确定一个最小数后按照上面的方法再一次寻找最小值,最后输出排序后的数。
#include<iostream>
using namespace std;
#define N 10
int main()
{
int a[N];//定义数组用来储存输入要排序的数
for(int i=0;i<N;i++)
{
cin>>a[i];
}//用一个for循环要排序的数
cout<<"排序前为:"<<endl;
for(int i=1;i<N;i++)
{
cout<<a[i]<<"\t";
} //输出排序前的数
cout<<endl;
for(int i=0;i<N;i++)
{
for(int j=0;j<N-i;j++)
{
if(a[j]>a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}//冒泡排序
cout<<"排序后为:"<<endl;
for(int i=0;i<N;i++)
{
cout<<a[i]<<"\t";
}//输出排序后的数
return 0;
}
运行结果如下: