TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
bitonic_sort.cpp
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 <algorithm>
7#include <iostream>
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.*/
12void compAndSwap(int a[], int i, int j, int dir) {
13 if (dir == (a[i] > a[j]))
14 std::swap(a[i], a[j]);
15}
16
17/*It recursively sorts a bitonic sequence in ascending order,
18 if dir = 1, and in descending order otherwise (means dir=0).
19 The sequence to be sorted starts at index position low,
20 the parameter cnt is the number of elements to be sorted.*/
21void bitonicMerge(int a[], int low, int cnt, int dir) {
22 if (cnt > 1) {
23 int k = cnt / 2;
24 for (int i = low; i < low + k; i++) compAndSwap(a, i, i + k, dir);
25 bitonicMerge(a, low, k, dir);
26 bitonicMerge(a, low + k, k, dir);
27 }
28}
29
30/* This function first produces a bitonic sequence by recursively
31 sorting its two halves in opposite sorting orders, and then
32 calls bitonicMerge to make them in the same order */
33void bitonicSort(int a[], int low, int cnt, int dir) {
34 if (cnt > 1) {
35 int k = cnt / 2;
36
37 // sort in ascending order since dir here is 1
38 bitonicSort(a, low, k, 1);
39
40 // sort in descending order since dir here is 0
41 bitonicSort(a, low + k, k, 0);
42
43 // Will merge wole sequence in ascending order
44 // since dir=1.
45 bitonicMerge(a, low, cnt, dir);
46 }
47}
48
49/* Caller of bitonicSort for sorting the entire array of
50 length N in ASCENDING order */
51void sort(int a[], int N, int up) { bitonicSort(a, 0, N, up); }
52
53// Driver code
54int main() {
55 int a[] = {3, 7, 4, 8, 6, 2, 1, 5};
56 int N = sizeof(a) / sizeof(a[0]);
57
58 int up = 1; // means sort in ascending order
59 sort(a, N, up);
60
61 std::cout << "Sorted array: \n";
62 for (int i = 0; i < N; i++) std::cout << a[i] << " ";
63 return 0;
64}
double k(double x)
Another test function.
int main()
Main function.
constexpr uint32_t N
A struct to represent sparse table for min() as their invariant function, for the given array A....