zoukankan      html  css  js  c++  java
  • 排序算法之冒泡排序

    概念

    两两比较相邻记录的关键字,如果反序则交换,直到没有反序的记录为止。

    Java版实现

    原版冒泡排序算法

        public static void bubbling1(Integer[] array) {
            for (int n = (array.length-1); n > 0; n--) {
                System.out.println("Bubbling.bubbling1() need to do comparing");
                for (int i = 0; i < n; i++) {                
                    int j = i+1;
                    if (array[i] > array[j]) Helper.swap(array, i, j);                
                } // end for compare n times
            } // end for loop the length-1 times
        }
    

    两两比较,循环n-1次

    改进版冒泡排序算法

        public static void bubbling2(Integer[] array){        
            Boolean status = true;
            for (int n = (array.length-1); n > 0 && status; n--) {
                System.out.println("Bubbling.bubbling1() need to do comparing");
                status = false;
                for (int i = 0; i< n; i++) {
                    int j = i + 1;
                    if (array[i] > array[j]) {
                        Helper.swap(array, i, j);
                        status = true;
                    } // end if the i>j
                } // end for compare n times    
            } // end for loop length-1 times
        }
    

    两两比较,若某次循环没有任何交换,则认为排序完成

    时间复杂度分析

    最好的情况,即本来就是有序序列,用优化算法,只需要比较n-1次,移动0次,时间复杂度为O(n)

    最坏的情况,即本来为倒序序列,用优化算法,需要比较和移动n(n-1)/2次,时间复杂度为O(n2)                              

    空间复杂度分析

    用于交换的辅助空间为O(1)                                                                  

  • 相关阅读:
    Java魔法堂:String.format详解
    Postgresql 正则表达式
    Linux下安装LAMP(Apache+PHP+MySql)和禅道
    Redis 启动警告错误解决[转]
    Postgresql: UUID的使用
    在Linux下安装RabbitMQ
    Python的包管理工具Pip
    在Linux CentOS 6.6上安装RedisLive
    [转]在Linux CentOS 6.6上安装Python 2.7.9
    在Linux上rpm安装运行Redis 3.0.4
  • 原文地址:https://www.cnblogs.com/scarlettxu/p/3486663.html
Copyright © 2011-2022 走看看