zoukankan      html  css  js  c++  java
  • 排序-冒泡排序

    思想

    • 基本思想: 冒泡排序,类似于水中冒泡,较大的数沉下去,较小的数慢慢冒起来,假设从小到大,即为较大的数慢慢往后排,较小的数慢慢往前排。
    • 直观表达,每一趟遍历,将一个最大的数移到序列末尾。

    算法描述

    1. 比较相邻的元素,如果前一个比后一个大,交换之。
    2. 第一趟排序第1个和第2个一对,比较与交换,随后第2个和第3个一对比较交换,这样直到倒数第2个和最后1个,将最大的数移动到最后一位。
    3. 第二趟将第二大的数移动至倒数第二位
      ......
      因此需要n-1趟;
      动图实现,(来源参考资料)
      enter image description here

    代码实现(java)

    /**
     * @ClassName: BubbleSortMain
     * @Author: fanjiajia
     * @Date: 2019/3/4 下午9:15
     * @Version: 1.0
     * @Description: 冒泡排序
     */
    
    import com.jiajia.ArrayUtil.*;  // 按包名导入
    
    public class BubbleSortMain {
    
        public static void main(String[] args) {
            int[] arr = {2,5,1,3,8,5,7,4,3};
            bubbleSort(arr);
    
            ArrayUtil.print(arr);
    
        }
    
        /**
         * 冒泡排序
         * @param arr
         */
        private static void bubbleSort(int[] arr) {
            for (int i = 0; i < arr.length; i++) {
                for (int j = 0; j < arr.length - i -1; j++) {   // 这里说明为什么需要-1
                    if (arr[j] > arr[j + 1]) {
                        int temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
            }
        }
    }
    
    

    复杂度

    时间复杂度: $O(N^2)$
    空间复杂度: $O(1)$

    参考资料

    https://www.toutiao.com/a6593273307280179715/?iid=6593273307280179715

    最后

    此致,敬礼

  • 相关阅读:
    hsdis反汇编java源码工具的使用方法
    final添加内存屏障问题
    Spring-AOP
    Spring-IOC
    IO与NIO
    设计模式学习笔记
    Redis学习笔记
    MySQL优化
    STAR法则
    大文件分割之Linux
  • 原文地址:https://www.cnblogs.com/numen-fan/p/10473576.html
Copyright © 2011-2022 走看看