-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheven_odd_sort_open_mp.cpp
More file actions
82 lines (66 loc) · 2.09 KB
/
even_odd_sort_open_mp.cpp
File metadata and controls
82 lines (66 loc) · 2.09 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "even_odd_sort_open_mp.hpp"
even_odd_sort_open_mp::even_odd_sort_open_mp(int _nthreads) : sortable(_nthreads) { }
std::string even_odd_sort_open_mp::name() const {
return "Even odd sort -- OpenMP --";
}
void even_odd_sort_open_mp::sort_array(int array[], int n){
std::pair<int, int>* indices = new std::pair<int, int>[nthreads];
int nelements = static_cast<int>(ceil(static_cast<double>(n) / static_cast<double>(nthreads))); // ceil(7 / 4) = 2
int start = 0, stop = nelements;
int segment_count = 0;
for(int x=0; x<nthreads && start < n; x++, start += nelements, stop += nelements) {
indices[x] = std::make_pair(start, std::min(stop, n));
segment_count++;
}
#pragma omp parallel num_threads(nthreads)
{
#pragma omp for
for (int x = 0; x < segment_count; x++) {
even_odd_sort_open_mp::sort_thread(array, indices[x].first, indices[x].second);
}
}
if(segment_count < 2) {
//no need to do an even-odd merge if there are not at least two segments to merge
return;
}
for(int start_index = 0, y=0; y<nthreads; start_index = (start_index + 1) % 2, y++) {
int thread_count = 0;
int max = std::min(nthreads, segment_count) - 1;
#pragma omp parallel num_threads(nthreads)
{
#pragma omp for
for(int x=start_index; x < max; x+=2) {
even_odd_sort_open_mp::merge_thread(array, indices[x].first, indices[x].second, indices[x+1].second);
}
}
}
delete[] indices;
}
void even_odd_sort_open_mp::sort_thread(int array[], int start, int stop){
std::sort(array + start, array + stop);
}
void even_odd_sort_open_mp::merge_thread(int array[], int start, int mid, int stop){
int* tmp = new int[stop - start];
int pa = start;
int pb = mid;
int x = 0;
while(pa < mid && pb < stop){
int a = array[pa];
int b = array[pb];
if(a <= b){
pa++;
tmp[x++] = a;
} else {
pb++;
tmp[x++] = b;
}
}
while(pa < mid){
tmp[x++] = array[pa++];
}
while(pb < stop){
tmp[x++] = array[pb++];
}
std::copy(tmp, tmp + (stop - start), array + start);
delete[] tmp;
}