-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge_sort_openmp.cpp
99 lines (78 loc) · 1.39 KB
/
merge_sort_openmp.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
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <omp.h>
#define SIZE 10
using namespace std;
void init_arr(int *inp, int n);
void merge_sort(int *inp, int* out, int n);
void merge(int *inp, int* out, int n);
void print(int *inp, int n);
int main()
{
int *arr = new int[SIZE];
int *tmp = new int[SIZE];
init_arr(arr, SIZE);
merge_sort(arr, tmp, SIZE);
print(arr, SIZE);
return 0;
}// End of main function
void init_arr(int *inp, int n)
{
time_t t;
srand((unsigned) time(&t));
int i;
for(i = 0; i < n; i++)
{
inp[i] = rand()%100;
}
}// End of init_arr function
void merge_sort(int *inp, int* out, int n)
{
if(n < 2)
return;
#pragma omp parallel sections
{
#pragma omp section
{
merge_sort(inp, out, n/2);
}
#pragma omp section
{
merge_sort(inp+(n/2), out+(n/2), n-(n/2));
}
}
merge(inp, out, n);
}// End of merge_sort function
void merge(int *inp, int* out, int n)
{
int i, j, k=0;
i = 0; j = n/2;
while(i < n/2 && j < n)
{
if(inp[i] <= inp[j])
out[k++] = inp[i++];
else
out[k++] = inp[j++];
}
while(i < n/2)
{
out[k++] = inp[i++];
}
while(j < n)
{
out[k++] = inp[j++];
}
memcpy(inp, out, n*sizeof(int));
}// End of merge function
void print(int *inp, int n)
{
int i;
cout<<"\n Sorted array: \n";
for(i = 0; i < n; i++)
{
cout<<" "<<inp[i]<<" ";
}
cout<<"\n";
}// End of print function