日期:2014-05-20 浏览次数:21178 次
public class Mp {
public static void main(String args[]){
// for(int i=0;i<a.length;i++){
// a[i]=Integer.parseInt(JOptionPane.showInputDialog(null,"请输入初始数据"));
// }
int a[] = {8,2,5,6,4,1};
fun(a);
System.out.print("最后结果:");
printArray(a);
}
static void printArray(int a[]){
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
static void fun(int a[]){
for(int j=0;j<a.length-1;j++){
for(int i=0;i<a.length-j-1;i++){
if(a[i]>a[i+1]){
int t;
t=a[i];
a[i]=a[i+1];
a[i+1]=t;
}
}
System.out.print("第"+(j+1)+"次冒泡:");
printArray(a);
}
}
}
第1次冒泡:2 5 6 4 1 8
第2次冒泡:2 5 4 1 6 8
第3次冒泡:2 4 1 5 6 8
第4次冒泡:2 1 4 5 6 8
第5次冒泡:1 2 4 5 6 8
最后结果:1 2 4 5 6 8
------解决方案--------------------
因为,第一个for循环是,根据你排序数的多少控制循环的轮数,第二for循环是数据之间的相互比较。
------解决方案--------------------
第二for循环执行一次 只是把相邻的2个数比较,然后交换位置,
如果 最小的数在最后以为, 就需要第一个for循环执行多次把他换到第一个位置,
就像毛毛虫 一拱一拱的前进
------解决方案--------------------