-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpu_bitonic_sort.cpp
48 lines (40 loc) · 1.16 KB
/
cpu_bitonic_sort.cpp
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
#include <iostream>
#include <vector>
void compareAndSwap(std::vector<int>& arr, int i, int j, bool dir) {
if (dir == (arr[i] > arr[j])) {
std::swap(arr[i], arr[j]);
}
}
void bitonicMerge(std::vector<int>& arr, int low, int cnt, bool dir) {
if (cnt > 1) {
int k = cnt / 2;
for (int i = low; i < low + k; i++) {
compareAndSwap(arr, i, i + k, dir);
}
bitonicMerge(arr, low, k, dir);
bitonicMerge(arr, low + k, k, dir);
}
}
void bitonicSort(std::vector<int>& arr, int low, int cnt, bool dir) {
if (cnt > 1) {
int k = cnt / 2;
bitonicSort(arr, low, k, true);
bitonicSort(arr, low + k, k, false);
bitonicMerge(arr, low, cnt, dir);
}
}
void bitonicSort(std::vector<int>& arr) {
bitonicSort(arr, 0, arr.size(), true);
}
// Example usage
int main() {
std::vector<int> arr = {3, 7, 4, 8, 6, 2, 1, 5};
std::cout << "Original array: ";
for (int num : arr) std::cout << num << " ";
std::cout << std::endl;
bitonicSort(arr);
std::cout << "Sorted array: ";
for (int num : arr) std::cout << num << " ";
std::cout << std::endl;
return 0;
}