本文實例講述了java交換排序之雞尾酒排序實現方法。分享給大家供大家參考。具體如下:
雞尾酒排序,也就是定向冒泡排序, 雞尾酒攪拌排序, 攪拌排序 (也可以視作選擇排序的一種變形), 漣漪排序, 來回排序 or 快樂小時排序, 是冒泡排序的一種變形。此算法與冒泡排序的不同處在于排序時是以雙向在序列中進行排序。
與冒泡排序不同的地方:
雞尾酒排序等于是冒泡排序的輕微變形。不同的地方在于從低到高然后從高到低,而冒泡排序則僅從低到高去比較序列里的每個元素。他可以得到比冒泡排序稍微好一點的效能,原因是冒泡排序只從一個方向進行比對(由低到高),每次循環只移動一個項目。
以序列(2,3,4,5,1)為例,雞尾酒排序只需要訪問一次序列就可以完成排序,但如果使用冒泡排序則需要四次。 但是在亂數序列的狀態下,雞尾酒排序與冒泡排序的效率都很差勁。
最差時間復雜度 O(n^2)
最優時間復雜度 O(n)
平均時間復雜度 O(n^2)
雞尾酒排序動態圖如下:
代碼分析:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
package com.baobaotao.test; /** * 排序研究 * */ 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) ; } } /** * 雞尾酒排序(帶標志位) * @param array 傳入的數組 */ public static void cocatailSortFlag( int [] array) { int length = array.length ; boolean flag1,flag2 = true ; //來回循環length/2次 for ( int i= 0 ;i<length/ 2 ;i++) { flag1 = true ; flag2 = true ; for ( int j=i;j<length-i- 1 ;j++) { if (array[j] > array[j+ 1 ]) { swap(array, j, j+ 1 ) ; flag1 = false ; } } for ( int j=length-i- 1 ;j>i;j--) { if (array[j] < array[j- 1 ]) { swap(array, j- 1 , j) ; flag2 = false ; } } if (flag1 && flag2) { break ; } printArr(array) ; } } /** * 按從小到大的順序交換數組 * @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) ; } } |
結果分析:
1
2
3
4
5
6
7
8
|
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 11 12 15 24 45 51 78 84 95 ***************** 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次就可以完成排序。
希望本文所述對大家的java程序設計有所幫助。