冒泡排序的两种写法

本文介绍了冒泡排序的两种常见实现方法:一种是每次循环选出最小元素置于最前,另一种则是选出最大元素置于最后。尽管排序过程的交换次数相同,但外层循环的结束条件有所不同。详细解析及示例参考链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



    public static void main(String[] args) {
        int[] a = {5, 6, 3, 4, 8, 9, 13, 441, 8};
//        function1(a);
        function2(a);
    }

    public static void function1(int[] a) {
        int count1 = 0;
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = i + 1; j < a.length; j++) {
                int temp;
                if (a[i] > a[j]) {
                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                    count1++;
                    for (int m : a) {
                        System.out.print(m + "  ");
                    }
                    System.out.println("");
                }
            }
            System.out.println("第" + (i+1) + "次循环完成");
        }
        System.out.println("总共交换次数为"+count1+"次");
    }

    public static void function2(int[] arr) {
        int count2 = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    count2++;
                    for (int m : arr) {
                        System.out.print(m + "  ");
                    }
                    System.out.println("");
                }
            }
            System.out.println("第" + (i+1) + "次循环完成");
        }
        System.out.println("总共交换次数为"+count2+"次");
    }

结果

方法1(外层for循环每一次选出最小的放在最前面(下图的第一行结果就是外for的第一次循环完成))

方法2(外层for循环每一次选出最大的放在最后面(下图的前三行结果才是外for的第一次循环完成,从下图可以看出外循环其实3次就排好序了))

 

无论哪一种方法排序的次数是不变的,都交换了7次

 

可以参考

https://www.cnblogs.com/taotingkai/p/6214367.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值