-
Notifications
You must be signed in to change notification settings - Fork 1
/
mergeSortOMP.c
97 lines (84 loc) · 1.93 KB
/
mergeSortOMP.c
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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "omp.h"
#define MAX_SIZE 1024*1024
//Function for creating an input array||Update accoorind to your need
void generate_list(int * x, int n) {
int i,j,t;
for (i = 0; i < n; i++)
x[i] = i;
for (i = 0; i < n; i++) {
j = rand() % n;
t = x[i];
x[i] = x[j];
x[j] = t;
}
}
void print_list(int * x, int n) {
int i;
for (i = 0; i < n; i++) {
printf("%d ",x[i]);
}
printf("\n");
}
//Merging 2 sorted subarrays into one tmp array
void merge(int * X, int n, int * tmp) {
int i = 0;
int j = n/2;
int ti = 0;
//i will iterate till first half anf J will iterate for 2nd half of array
while (i<n/2 && j<n) {
if (X[i] < X[j]) {
tmp[ti] = X[i];
ti++; i++;
} else {
tmp[ti] = X[j];
ti++;
j++;
}
}
while (i<n/2) { /* finish up lower half */
tmp[ti] = X[i];
ti++;
i++;
}
while (j<n) { /* finish up upper half */
tmp[ti] = X[j];
ti++;
j++;
}
//Copy sorted array tmp back to X (Original array)
memcpy(X, tmp, n*sizeof(int));
} // end of merge()
void mergesort(int * X, int n, int * tmp)
{
if (n < 2) return;
#pragma omp task firstprivate (X, n, tmp)
mergesort(X, n/2, tmp);
#pragma omp task firstprivate (X, n, tmp)
mergesort(X+(n/2), n-(n/2), tmp);
//Wait for both paralel tasks to complete execution
#pragma omp taskwait
/* merge sorted halves into sorted list */
merge(X, n, tmp);
}
int main()
{
int n = 100;
double start, stop;
int *data = malloc(MAX_SIZE*sizeof(int));
int *tmp = malloc(MAX_SIZE*sizeof(int));
generate_list(data, n);
printf("List Before Sorting...\n");
print_list(data, n);
#pragma omp parallel num_threads(8)
{
#pragma omp single
mergesort(data, n, tmp);
}
printf("\nList After Sorting...\n");
print_list(data, n);
free(data);
free(tmp);
}