冒泡排序及其优化

#数据结构排序之冒泡排序
两两比较,大的往后走,小的往前走

  • 时间复杂度 O(n2)
  • 空间复杂度o(1);
  • 稳定性:稳定
  • 1 2 3 4 5
  • 优化
  • 用一个标志Flag实现
  • 有序只排一趟序

在这里插入图片描述

在这里插入代码片
public class BubbleTest {
    public static void BubbleSort(int[] array) {
        //趟数//n-1
        for (int i = 0; i < array.length; i++) {
            //一趟冒泡的过程
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j + 1] < array[j]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;

                }

            }
        }

    }
    public  static  void optimizedBubbleSort(int [] array) {
        if (array == null || array.length == 0) {
            return ;
        }
        //趟数
        boolean needNextSort = true;
        for (int i = 0; i < array.length - 1 && needNextSort; i++) {
            //一趟冒泡的过程
            needNextSort = false;
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    int tmp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = tmp;
                    needNextSort = true;
                }
            }
        }

    }

    public static void main(String[] args) {
        int [] array={10,6,8,2,3,0,10,15,29,9};
        BubbleSort(array);
        optimizedBubbleSort(array);
        System.out.println(Arrays.toString(array));
       System.out.println(Arrays.toString(array));
    }
}
//测试结果
[0, 2, 3, 6, 8, 9, 10, 10, 15, 29]
[0, 2, 3, 6, 8, 9, 10, 10, 15, 29]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值