Skip to content

Commit d72b48e

Browse files
authored
Create BitonicSort.cpp
1 parent aead0ba commit d72b48e

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

Sorting/BitonicSort.cpp

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
2+
/* C++ Program for Bitonic Sort. Note that this program
3+
works only when size of input is a power of 2. */
4+
5+
#include<stdio.h>
6+
#include<algorithm.h>
7+
using namespace std;
8+
9+
/*The parameter dir indicates the sorting direction, ASCENDING
10+
or DESCENDING; if (a[i] > a[j]) agrees with the direction,
11+
then a[i] and a[j] are interchanged.*/
12+
void compAndSwap(int a[], int i, int j, int dir)
13+
{
14+
if (dir==(a[i]>a[j]))
15+
swap(a[i],a[j]);
16+
}
17+
18+
/*It recursively sorts a bitonic sequence in ascending order,
19+
if dir = 1, and in descending order otherwise (means dir=0).
20+
The sequence to be sorted starts at index position low,
21+
the parameter cnt is the number of elements to be sorted.*/
22+
void bitonicMerge(int a[], int low, int cnt, int dir)
23+
{
24+
if (cnt>1)
25+
{
26+
int k = cnt/2;
27+
for (int i=low; i<low+k; i++)
28+
compAndSwap(a, i, i+k, dir);
29+
bitonicMerge(a, low, k, dir);
30+
bitonicMerge(a, low+k, k, dir);
31+
}
32+
}
33+
34+
/* This function first produces a bitonic sequence by recursively
35+
sorting its two halves in opposite sorting orders, and then
36+
calls bitonicMerge to make them in the same order */
37+
void bitonicSort(int a[],int low, int cnt, int dir)
38+
{
39+
if (cnt>1)
40+
{
41+
int k = cnt/2;
42+
43+
// sort in ascending order since dir here is 1
44+
bitonicSort(a, low, k, 1);
45+
46+
// sort in descending order since dir here is 0
47+
bitonicSort(a, low+k, k, 0);
48+
49+
// Will merge wole sequence in ascending order
50+
// since dir=1.
51+
bitonicMerge(a,low, cnt, dir);
52+
}
53+
}
54+
55+
/* Caller of bitonicSort for sorting the entire array of
56+
length N in ASCENDING order */
57+
void sort(int a[], int N, int up)
58+
{
59+
bitonicSort(a,0, N, up);
60+
}
61+
62+
// Driver code
63+
int main()
64+
{
65+
int a[]= {3, 7, 4, 8, 6, 2, 1, 5};
66+
int N = sizeof(a)/sizeof(a[0]);
67+
68+
int up = 1; // means sort in ascending order
69+
sort(a, N, up);
70+
71+
printf("Sorted array: \n");
72+
for (int i=0; i<N; i++)
73+
printf("%d ", a[i]);
74+
return 0;
75+
}

0 commit comments

Comments
 (0)