冒泡排序

来源:互联网 发布:c语言也能干大事 网盘 编辑:程序博客网 时间:2024/06/06 12:40
package niu.cheng2;
//冒泡排序
public class StringBuilder1 {

public static void main(String[] args) {
int[] x={7,6,5,4,3,2,1};
Fe(x);
System.out.println("---------------");
//冒泡排序
/*
for(int x1=0;x1<x.length-1-0;x1++){
if(x[x1]>x[x1+1]){
int a=x[x1];
x[x1] = x[x1+1];
x[x1+1]=a;
}
}
System.out.println("第一次排序后");
Fe(x);
for(int x1=0;x1<x.length-1-1;x1++){
if(x[x1]>x[x1+1]){
int a=x[x1];
x[x1] = x[x1+1];
x[x1+1]=a;
}
}
System.out.println("第二次排序后");
Fe(x);
for(int x1=0;x1<x.length-1-2;x1++){
if(x[x1]>x[x1+1]){
int a=x[x1];
x[x1] = x[x1+1];
x[x1+1]=a;
}
}
System.out.println("第三次排序后");
Fe(x);
for(int x1=0;x1<x.length-1-3;x1++){
if(x[x1]>x[x1+1]){
int a=x[x1];
x[x1] = x[x1+1];
x[x1+1]=a;
}
}
System.out.println("第四次排序后");
Fe(x);
for(int x1=0;x1<x.length-1-4;x1++){
if(x[x1]>x[x1+1]){
int a=x[x1];
x[x1] = x[x1+1];
x[x1+1]=a;
}
}
System.out.println("第五次排序后");
Fe(x);
for(int x1=0;x1<x.length-1-5;x1++){
if(x[x1]>x[x1+1]){
int a=x[x1];
x[x1] = x[x1+1];
x[x1+1]=a;
}
}
System.out.println("第五次排序后");
Fe(x);
//代码重复度太高,用循环改进。
*/

//最终代码
for(int y=0;y<x.length-1;y++){
for(int x1=0;x1<x.length-1-y;x1++){
if(x[x1]>x[x1+1]){
int a=x[x1];
x[x1] = x[x1+1];
x[x1+1]=a;
}
}
}
System.out.println("冒泡排序之后结果为:");
Fe(x);
}
public static void Fe(int[] x){
System.out.print("[");
for(int y=0;y<x.length;y++){
if(y==x.length-1){
System.out.print(x[y]);
break;
}else{
System.out.print(x[y]+",");
}
}
System.out.println("]");


}
}
0 0
原创粉丝点击