冒泡排序

冒泡排序

冒泡排序的原理动图请大家自行百度,本博客仅剖析实现

八大排序算法中最为出名的排序算法即冒泡排序

实现即两层循环,外层冒泡轮数,里层依次比较,江湖中人尽皆知

看到嵌套循环,应该立马可以得出这个算法的时间复杂度为O(n2)

代码实现

package com.example.demo_kuang.array;

import java.util.Arrays;

public class ArrayDemo {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 1999, 24, 45};
        System.out.println(nums); //[I@72ea2f77
        System.out.println(Arrays.toString(nums));
        System.out.println(Arrays.toString(sort(nums)));
    }

    public static int[] sort(int[] nums) {
        int temp = 0;

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

如何优化?

如果一个排列好的数组,怎么优化,可以添加一个标志,如果内层for循环里面的if语句没有生效过,则直接返回,代码请自己练习

posted @ 2021-10-29 10:03  Oh,mydream!  阅读(26)  评论(0编辑  收藏  举报