-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_sort_openmp.cpp
More file actions
101 lines (80 loc) · 1.64 KB
/
quick_sort_openmp.cpp
File metadata and controls
101 lines (80 loc) · 1.64 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <omp.h>
#define SIZE 10
using namespace std;
void init_arr(int *inp, int n);
void quick_sort(int low, int high, int *inp);
int partition(int low, int high, int *inp);
void print(int *inp, int n);
int main()
{
int *arr = new int[SIZE];
init_arr(arr, SIZE);
quick_sort(0, SIZE-1, arr);
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 quick_sort(int low, int high, int *inp)
{
int j;
if(low < high)
{
j = partition(low, high, inp);
#pragma omp parallel sections
{
#pragma omp section //sort left sublist
{
quick_sort(low, j-1, inp);
}
#pragma omp section //sort right sublist
{
quick_sort(j+1, high, inp);
}
}
}
}// End of quick_sort function
int partition(int low, int high, int *inp)
{
int i, j, pivot, tmp;
pivot=low; i=low+1; j=high;
while(1)
{
while(i<high && inp[i]<=inp[pivot])
i++;
while(inp[j] > inp[pivot])
j--;
if(i < j)
{
//Swap i and j position element
tmp = inp[i]; inp[i] = inp[j]; inp[j] = tmp;
}
else
{
//Swap j and pivot position element
tmp = inp[j]; inp[j] = inp[pivot]; inp[pivot] = tmp;
return j;
}
}
}// End of partition 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