• 算法


    重点:依次对比邻近值,将较大/较小值向一侧移动

    public class BubbleSort<T extends Comparable> {
    
        public void sort(T[] arr) {
            if (arr != null && arr.length > 1) {
                for (int i = 0; i < arr.length; i++) {
                    int j = 0;
                    for (; j < arr.length - 1 - i; j++) {
                        if (arr[j].compareTo(arr[j + 1]) > 0) {
                            T temp = arr[j + 1];
                            arr[j + 1] = arr[j];
                            arr[j] = temp;
                            for (T n : arr) {
                                System.out.print(n);
                            }
                            System.out.println();
                        }
                    }
                    System.out.println(String.format("第%d次交换,遍历了%d次", i + 1, j));
                }
            }
        }
    
        public static void main(String[] args) {
            Integer[] arr = new Integer[]{1, 3, 8, 7, 6, 9, 5, 4, 3, 2, 0};
            BubbleSort bs = new BubbleSort();
            bs.sort(arr);
        }
    
        /**
         * 13786954320 => 原数组,11个元素
         *    ^^       => 8比6大,交换
         * 13768954320
         *      ^^     => 9比5大,交换
         * 13768594320
         *       ^^    => 9比4大,交换
         * 13768549320
         *        ^^   => 9比3大,交换
         * 13768543920
         *         ^^  => 9比2大,交换
         * 13768543290
         *          ^^ => 9比0大,交换,后同
         * 13768543209
         * 第1次交换,遍历了10次
         * 13678543209
         * 13675843209
         * 13675483209
         * 13675438209
         * 13675432809
         * 13675432089
         * 第2次交换,遍历了9次
         * 13657432089
         * 13654732089
         * 13654372089
         * 13654327089
         * 13654320789
         * 第3次交换,遍历了8次
         * 13564320789
         * 13546320789
         * 13543620789
         * 13543260789
         * 13543206789
         * 第4次交换,遍历了7次
         * 13453206789
         * 13435206789
         * 13432506789
         * 13432056789
         * 第5次交换,遍历了6次
         * 13342056789 => 3从后方移动过来,原顺序未改变,因此稳定
         * 13324056789
         * 13320456789
         * 第6次交换,遍历了5次
         * 13230456789
         * 13203456789
         * 第7次交换,遍历了4次
         * 12303456789
         * 12033456789
         * 第8次交换,遍历了3次
         * 10233456789
         * 第9次交换,遍历了2次
         * 01233456789
         * 第10次交换,遍历了1次
         * 第11次交换,遍历了0次
         *
         * 最外层遍历了11次,最内层遍历了10 + 9 + ... + 1
         * => 遍历次数:n(n - 1)/2
         * => 时间复杂度:O(n2)
         * => 稳定性:稳定
         */
    
    }
  • 相关阅读:
    Python 写Windows Service服务程序
    关于Python 获取windows信息收集
    Pyqt 获取windows系统中已安装软件列表
    Python 打开目录与指定文件
    【转载】Pyqt 编写的俄罗斯方块
    Python win32api提取exe图标icon
    Pyqt QListWidget之缩略图列表
    Pyqt 时时CPU使用情况
    Python 的三目运算
    Chrome Crx 插件下载
  • 原文地址:https://www.cnblogs.com/SamNicole1809/p/12793713.html
Copyright © 2020-2023  润新知