Skip to content

Commit 37326e9

Browse files
authored
Merge pull request #114 from Aruj-Sharma/master
Added Bitonic Sort
2 parents 1d90764 + 293a9bf commit 37326e9

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

Sorting/BitonicSort.cpp

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

0 commit comments

Comments
 (0)