Skip to content

Commit b53a0f7

Browse files
authored
Create parallelbubblesort.cpp
Parallel Bubble Sort algorithm using openmp in C++.
1 parent 72cb320 commit b53a0f7

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

parallelbubblesort.cpp

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#include<bits/stdc++.h>
2+
#include<omp.h>
3+
#include<chrono>
4+
using namespace std;
5+
using namespace std::chrono;
6+
typedef long long ll;
7+
8+
void sbubble(int arr[],int n){
9+
time_point<system_clock> start,end;
10+
start=system_clock::now();
11+
for(int i=0;i<n;i++){
12+
for(int j=0;j<n;j++){
13+
if(arr[j]>arr[j+1]){
14+
int temp=arr[j];
15+
arr[j]=arr[j+1];
16+
arr[j+1]=temp;
17+
}
18+
}
19+
}
20+
end=system_clock::now();
21+
duration<double> time=end-start;
22+
23+
cout<<"Serial Bubble Sort time is: "<<time.count()*1000<<"\n";
24+
}
25+
26+
27+
void pbubble(int arr[],int n){
28+
29+
omp_set_num_threads(2);
30+
int first=0;
31+
time_point<system_clock> start,end;
32+
start=system_clock::now();
33+
for(int i=0;i<n;i++){
34+
first=i%2;
35+
#pragma omp parallel for default(none),shared(arr,first,n)
36+
for(int j=first;j<n;j++){
37+
if(arr[j]>arr[j+1]){
38+
int temp=arr[j];
39+
arr[j]=arr[j+1];
40+
arr[j+1]=temp;
41+
}
42+
}
43+
}
44+
end=system_clock::now();
45+
duration<double> time=end-start;
46+
47+
cout<<"Paralel Bubble Sort time is: "<<time.count()*1000<<"\n";
48+
}
49+
50+
int main(){
51+
int n;
52+
cout<<"Enter the size of the random array to be generated\n";
53+
cin>>n;
54+
55+
int *a=new int[n];
56+
int *b=new int[n];
57+
int in=0,in1=0;
58+
for(int i=n-1;i>=0;i--){
59+
a[in++]=i;
60+
b[in1++]=i;
61+
}
62+
63+
64+
65+
sbubble(a,n);
66+
pbubble(b,n);
67+
68+
return 0;
69+
}
70+
71+
72+
/* Execution:
73+
74+
1. Open terminal
75+
2. g++ -std=c++14 -fopenmp parallelbubblesort.cpp
76+
3. ./a.out
77+
78+
Enter the size of the random array to be generated
79+
20000
80+
Serial Bubble Sort time is: 2406.04 milliseconds
81+
Paralel Bubble Sort time is: 1529.21 milliseconds
82+
83+
*/

0 commit comments

Comments
 (0)