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

    最后

    此致,敬礼

  • 相关阅读:
    java中的迭代器的含义
    angular-指令总结
    angular-ng-model
    angular-创建自定义的指令
    angular-$scope和$rootScope
    angular-过滤器
    Git-pull进入vim窗口解决办法
    Math常用方法
    全局变量和window属性上定义的变量
    透明点点的轮播图
  • 原文地址:https://www.cnblogs.com/numen-fan/p/10473576.html
Copyright © 2011-2022 走看看