Java--冒泡排序

/**
 * 冒泡排序
 */

import java.util.Arrays;

public class BubbleSort {
    public static void main(String[] args) {
        int[] values={3,1,6,2,9,0,7,4,5,8};
        int temp=0;
        for(int i=0;i<values.length-1;i++){

            boolean flag=true;  //优化排序,减少不必要的比较
            System.out.println("######"+"第"+(i+1)+"趟"+"  "+"比较"+(values.length-i-1)+"次");

            for(int j=0;j<values.length-1-i;j++){
                if(values[j]>values[j+1]){
                    temp=values[j];
                    values[j]=values[j+1];
                    values[j+1]=temp;

                    flag=false;
                }
                System.out.println(Arrays.toString(values));

            }
            if(flag){
                System.out.println("结束!!!");
                break;
            }
        }
    }
}
运行结果
######第1趟  比较9[1, 3, 6, 2, 9, 0, 7, 4, 5, 8]
[1, 3, 6, 2, 9, 0, 7, 4, 5, 8]
[1, 3, 2, 6, 9, 0, 7, 4, 5, 8]
[1, 3, 2, 6, 9, 0, 7, 4, 5, 8]
[1, 3, 2, 6, 0, 9, 7, 4, 5, 8]
[1, 3, 2, 6, 0, 7, 9, 4, 5, 8]
[1, 3, 2, 6, 0, 7, 4, 9, 5, 8]
[1, 3, 2, 6, 0, 7, 4, 5, 9, 8]
[1, 3, 2, 6, 0, 7, 4, 5, 8, 9]
######第2趟  比较8[1, 3, 2, 6, 0, 7, 4, 5, 8, 9]
[1, 2, 3, 6, 0, 7, 4, 5, 8, 9]
[1, 2, 3, 6, 0, 7, 4, 5, 8, 9]
[1, 2, 3, 0, 6, 7, 4, 5, 8, 9]
[1, 2, 3, 0, 6, 7, 4, 5, 8, 9]
[1, 2, 3, 0, 6, 4, 7, 5, 8, 9]
[1, 2, 3, 0, 6, 4, 5, 7, 8, 9]
[1, 2, 3, 0, 6, 4, 5, 7, 8, 9]
######第3趟  比较7[1, 2, 3, 0, 6, 4, 5, 7, 8, 9]
[1, 2, 3, 0, 6, 4, 5, 7, 8, 9]
[1, 2, 0, 3, 6, 4, 5, 7, 8, 9]
[1, 2, 0, 3, 6, 4, 5, 7, 8, 9]
[1, 2, 0, 3, 4, 6, 5, 7, 8, 9]
[1, 2, 0, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 0, 3, 4, 5, 6, 7, 8, 9]
######第4趟  比较6[1, 2, 0, 3, 4, 5, 6, 7, 8, 9]
[1, 0, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 0, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 0, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 0, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 0, 2, 3, 4, 5, 6, 7, 8, 9]
######第5趟  比较5[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
######第6趟  比较4[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
结束!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值