排序算法之冒泡排序

概念

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

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)                                                                  

原文地址:https://www.cnblogs.com/scarlettxu/p/3486663.html