forked from pratyushmp/code_opensource_2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitonicSort.java
More file actions
66 lines (55 loc) · 1.46 KB
/
BitonicSort.java
File metadata and controls
66 lines (55 loc) · 1.46 KB
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
public class BitonicSort
{
void compAndSwap(int a[], int i, int j, int dir)
{
if ( (a[i] > a[j] && dir == 1) ||
(a[i] < a[j] && dir == 0))
{
// Swapping elements
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
void bitonicMerge(int a[], int low, int cnt, int dir)
{
if (cnt>1)
{
int k = cnt/2;
for (int i=low; i<low+k; i++)
compAndSwap(a,i, i+k, dir);
bitonicMerge(a,low, k, dir);
bitonicMerge(a,low+k, k, dir);
}
}
void bitonicSort(int a[], int low, int cnt, int dir)
{
if (cnt>1)
{
int k = cnt/2;
bitonicSort(a, low, k, 1);
bitonicSort(a,low+k, k, 0);
bitonicMerge(a, low, cnt, dir);
}
}
void sort(int a[], int N, int up)
{
bitonicSort(a, 0, N, up);
}
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[])
{
int a[] = {3, 7, 4, 8, 6, 2, 1, 5};
int up = 1;
BitonicSort ob = new BitonicSort();
ob.sort(a, a.length,up);
System.out.println("\nSorted array");
printArray(a);
}
}