1
+ // Bitonic Sort
2
+ //this program works when size of input is power of 2.
3
+ public class BitonicSort
4
+ {
5
+ static void exchange (int arr [], int i , int j , boolean d )
6
+ {
7
+ int temp ;
8
+ if (d ==(arr [i ]>arr [j ]))
9
+ {
10
+ temp = arr [i ];
11
+ arr [i ] = arr [j ];
12
+ arr [j ] = temp ;
13
+ }
14
+ }
15
+ /* The sequence to be sorted starts at
16
+ index position low (l), the parameter c is the number
17
+ of elements to be sorted.*/
18
+ static void bitonicMerge (int arr [], int l , int c , boolean d )
19
+ {
20
+ int k ,i ;
21
+ if (c >1 )
22
+ {
23
+ k = c /2 ;
24
+ for (i =l ; i <l +k ; i ++)
25
+ exchange (arr , i , i +k , d );
26
+ bitonicMerge (arr , l , k , d );
27
+ bitonicMerge (arr , l +k , k , d );
28
+ }
29
+ }
30
+ static void bitonicSort (int arr [],int l , int c , boolean d )
31
+ {
32
+ int k ;
33
+ if (c >1 )
34
+ {
35
+ k = c /2 ;
36
+ // sort in ascending order since dir here is 1
37
+ bitonicSort (arr , l , k , true );
38
+
39
+ // sort in descending order since dir here is 0
40
+ bitonicSort (arr , l +k , k , false );
41
+
42
+ // Will merge whole sequence in ascending order since dir=1.
43
+ bitonicMerge (arr ,l , c , d );
44
+ }
45
+ }
46
+ /*Caller of bitonicSort for sorting the entire array
47
+ of length N in ASCENDING order */
48
+
49
+ static void sort (int arr [], int n , boolean order )
50
+ {
51
+ bitonicSort (arr ,0 , n , order );
52
+ }
53
+
54
+ /* A utility function to print array of size n */
55
+ static void printArray (int arr [])
56
+ {
57
+ int n = arr .length ;
58
+ for (int i =0 ; i <n ; ++i )
59
+ System .out .print (arr [i ] + " " );
60
+ System .out .println ();
61
+ }
62
+
63
+ // Driver Code
64
+
65
+ public static void main (String [] args )
66
+ {
67
+ int arr []= {1 , 10 , 2 , 3 , 1 , 23 , 45 , 21 };
68
+ int n = arr .length ;
69
+ int i ;
70
+ boolean order = true ;
71
+ sort (arr , n , order );
72
+
73
+ System .out .println ("Sorted array: \n " );
74
+ for (i =0 ; i <n ; i ++)
75
+ System .out .println (arr [i ]);
76
+ }
77
+ }
0 commit comments