-
Notifications
You must be signed in to change notification settings - Fork 0
/
OpenMP_Merge_Sort.c
131 lines (118 loc) · 1.95 KB
/
OpenMP_Merge_Sort.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include<stdio.h>
#include<stdlib.h>
#include<omp.h>
#include<time.h>
int num=0;
int *A;
int *temp;
int i;
void MergeSort(int arr[],int length)
{
A=(int*)malloc(length*sizeof(int));
temp=(int*)malloc(length*sizeof(int));
#pragma omp parallel num_threads(4)
{
#pragma omp for
for(i=0;i<length;i++)
{
A[i]=arr[i];
temp[i]=arr[i];
}
}
}
void merge(int start,int mid,int end)
{
int k, t;
int i=start;
int j=mid+1;
#pragma omp parallel num_threads(4)
{
#pragma omp for
for(t=start;t<=end;t++)
{
temp[t]=A[t];
}
}
#pragma omp parallel num_threads(4)
{
#pragma omp for
for(k=start;k<=end;k++)
{
if(i>mid){
A[k]=temp[j++];
}
else if(j>end){
A[k]=temp[i++];
}
else if(temp[i]<temp[j]){
A[k]=temp[i++];
}
else{
A[k]=temp[j++];
}
}
}
}
void display()
{
#pragma omp parallel num_threads(2)
{
#pragma omp for
for(i=0;i<=num;i++){
printf("%d ",A[i]);
}
}
}
void sort(int start, int end)
{
int mid;
#pragma omp parallel num_threads(2)
{
if(start<end)
{
mid=(start+end)/2;
sort(start,mid);
sort(mid+1,end);
merge(start,mid,end);
}
}
}
int main()
{
clock_t begin, end;
double total_t;
begin = clock();
int i;
num=0;
//int array[]={2,4,6,8,1,0,-5};
FILE *filepointer;
filepointer=fopen("1-25000.txt","r");
fscanf(filepointer, "%d",&num);
int *array=malloc(num*sizeof(int));
//int n=num;
for(i=0;i<=num;i++){
fscanf(filepointer,"%d",&array[i]);
}
printf("list before sorting \n");
#pragma omp parallel num_threads(4)
{
/*#pragma omp for
for(i=0;i<=num;i++)
{
printf("%d\n",array[i]);
}
*/
MergeSort(array,num);
sort(0,num);
}
printf("\n list after sorting\n");
display();
free(array);
end= clock();
total_t = (double)(end - begin );
//printf("Total numbers sorted: %d \n",num);
printf("\nInitial time taken by CPU: %d \n", begin );
printf("End time taken by CPU: %d \n", end );
printf("Total time taken by CPU: %f seconds\n", total_t );
return 0;
}