天天看點

排序進階之交換排序_雞尾酒排序

與冒泡排序不同的地方:

最差時間複雜度

排序進階之交換排序_雞尾酒排序

最優時間複雜度

排序進階之交換排序_雞尾酒排序

平均時間複雜度

排序進階之交換排序_雞尾酒排序

雞尾酒排序動态圖:

排序進階之交換排序_雞尾酒排序

代碼分析:

package com.baobaotao.test;  

/**  

 * 排序研究  

 * @author benjamin(吳海旭)  

 * @email [email protected] / [email protected]  

 *  

 */  

public class sort {  

    /**  

     * 經典雞尾酒排序  

     * @param array 傳入的數組  

     */  

    public static void cocatailsort(int[] array) {  

        int length = array.length ;  

        //來回循環length/2次  

        for(int i=0;i<length/2;i++) {  

            for(int j=i;j<length-i-1;j++) {  

                if(array[j] > array[j+1]) {  

                    swap(array, j, j+1) ;  

                }  

            }  

            for(int j=length-i-1;j>i;j--) {  

                if(array[j] < array[j-1]) {  

                    swap(array, j-1, j) ;  

            printarr(array) ;  

        }  

    }  

     * 雞尾酒排序(帶标志位)  

    public static void cocatailsortflag(int[] array) {  

        boolean flag1,flag2 = true ;  

            flag1 = true ;  

            flag2 = true ;  

                    flag1 = false ;  

                    flag2 = false ;  

            if(flag1 && flag2) {  

                break ;  

     * 按從小到大的順序交換數組  

     * @param a 傳入的數組  

     * @param b 傳入的要交換的數b  

     * @param c 傳入的要交換的數c  

    public static void swap(int[] a, int b, int c) {  

        int temp = 0 ;  

        if(b < c) {  

            if(a[b] > a[c]) {  

                temp = a[b] ;  

                a[b] = a[c] ;  

                a[c] = temp ;   

     * 列印數組  

     * @param array  

    public static void printarr(int[] array) {  

        for(int c : array) {  

            system.out.print(c + " ");  

        system.out.println();  

    public static void main(string[] args) {  

        int[] number={11,95,45,15,78,84,51,24,12} ;  

        int[] number2 = {11,95,45,15,78,84,51,24,12} ;  

        cocatailsort(number) ;  

        system.out.println("*****************");  

        cocatailsortflag(number2) ;  

}  

結果分析:

排序進階之交換排序_雞尾酒排序

11 12 45 15 78 84 51 24 95   

11 12 15 24 45 78 51 84 95   

11 12 15 24 45 51 78 84 95   

*****************  

可見雞尾酒排序排序的次數比普通冒泡排序要少很多。隻需要4次,用了改進版的标志位雞尾酒排序僅需要3次就可以完成排序。

轉載請注明:http://blog.csdn.net/benjamin_whx/article/details/42456279