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)                                                                  

  • 相关阅读:
    SpringMVC金课-课程大纲
    Type Cannot change version of project facet Dynamic Web Module to 3.0.
    使用maven 创建web项目 + 搭建SSM框架
    多文件上传
    asp.net 连接access数据库方法
    分享代码
    DIV+CSS解决IE6,IE7,IE8,FF兼容问题(转至http://www.douban.com/note/163291324/)
    asp.net发布网站(转)
    Img垂直居中
    http://www.apkbus.com/android-6231-1.html
  • 原文地址:https://www.cnblogs.com/scarlettxu/p/3486663.html
Copyright © 2011-2022 走看看