c++冒泡排序法
//冒泡排序法 #include<iostream> using namespace std; int main (){ int i,j,t,ii; int a[11]; //第0个元素始终没有用 cout<<"input 10 numbers:"<<endl; for(i=1;i<11;i++){ cin>>a[i]; //输入a[1]~a[10] } cout<<endl; for(j=1;j<=10;j++){ //共进行9趟比较 for(i=1;i<=11-j;i++){ //在每趟中要进行(10-j)次两两比较 if(a[i]<a[i+1]){ //如果后面的数大于前面的数 t=a[i]; a[i]=a[i+1]; a[i+1]=t; //交换两个数的位置,使大数上浮 } cout<<i<<"*"; } cout<<"array:"<<j<<endl; cout<<"the sroted numbers:"<<endl; for(i=1;i<11;i++){ cout<<a[i]<<" "; //输出10个数 } cout<<endl; } /* cout<<"the sroted numbers:"<<endl; for(i=1;i<11;i++){ cout<<a[i]<<" "; //输出10个数 } cout<<endl; */ system("PAUSE"); return 0; }
运行结果
input 10 numbers: 1 2 3 4 5 6 7 8 9 10 1*2*3*4*5*6*7*8*9*10*array:1 the sroted numbers: 2 3 4 5 6 7 8 9 10 1 1*2*3*4*5*6*7*8*9*array:2 the sroted numbers: 3 4 5 6 7 8 9 10 2 1 1*2*3*4*5*6*7*8*array:3 the sroted numbers: 4 5 6 7 8 9 10 3 2 1 1*2*3*4*5*6*7*array:4 the sroted numbers: 5 6 7 8 9 10 4 3 2 1 1*2*3*4*5*6*array:5 the sroted numbers: 6 7 8 9 10 5 4 3 2 1 1*2*3*4*5*array:6 the sroted numbers: 7 8 9 10 6 5 4 3 2 1 1*2*3*4*array:7 the sroted numbers: 8 9 10 7 6 5 4 3 2 1 1*2*3*array:8 the sroted numbers: 9 10 8 7 6 5 4 3 2 1 1*2*array:9 the sroted numbers: 10 9 8 7 6 5 4 3 2 1 1*array:10 the sroted numbers: 10 9 8 7 6 5 4 3 2 1 请按任意键继续. . .