package paixu;
//冒泡排序从小到大排序
public class maopao {
public static void main(String[] args) {
// TODO Auto-generated method stub
int shuzu[]={12,11,3,53,22,43,534};//创建数组
int i;
int j;
int temp;
for(i=0;i<shuzu.length-1;i++){
flag=0;
for(j=0;j<shuzu.length-1-i;j++){
if(shuzu[j]>shuzu[j+1]){
temp=shuzu[j];
shuzu[j]=shuzu[j+1];
shuzu[j+1]=temp;
flag=1;
}
}
}
for(int k=0;k<shuzu.length;k++){
System.out.print(shuzu[k]);
System.out.print(' ');
}
}
}
优化1:添加一个flag来减少循环次数
package paixu;
//冒泡排序从小到大排序
public class maopao {
public static void main(String[] args) {
// TODO Auto-generated method stub
int shuzu[]={12,11,3,53,22,43,534};//创建数组
int i;
int j;
int temp;
int flag=0;
for(i=0;i<shuzu.length-1;i++){
flag=0;
for(j=0;j<shuzu.length-1-i;j++){
if(shuzu[j]>shuzu[j+1]){
temp=shuzu[j];
shuzu[j]=shuzu[j+1];
shuzu[j+1]=temp;
flag=1;
}
}
if(flag==0){
break;
}
}
for(int k=0;k<shuzu.length;k++){
System.out.print(shuzu[k]);
System.out.print(' ');
}
}
}
优化二:记录下上次循环最后一次交换的位置
package paixu;
//冒泡排序从小到大排序
public class maopao {
public static void main(String[] args) {
// TODO Auto-generated method stub
int shuzu[]={12,11,3,53,22,43,534};//创建数组
int i;
int j;
int temp;
int flag=0;
int cos=shuzu.length-1;
int p=0;
for(i=0;i<shuzu.length-1;i++){
flag=0;
for(j=0;j<cos;j++){
if(shuzu[j]>shuzu[j+1]){
temp=shuzu[j];
shuzu[j]=shuzu[j+1];
shuzu[j+1]=temp;
flag=1;
p=j;
}
}
if(flag==0){
break;
}
cos=p;
}
for(int k=0;k<shuzu.length;k++){
System.out.print(shuzu[k]);
System.out.print(' ');
}
}
}
其实第一层循环用while更好。