i write a c++ code for Bubble sort algorithm and i dont know how to make it parallel using openmp so please help me ..... this is the code :
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <omp.h>
using namespace std;
int a[40001];
void sortArray(int [], int);
int q=0;
int _tmain(int argc, _TCHAR* argv[])
{
int x=40000;
int values[40000];
for (int i=0;i<x;i++)
{
values[i]=rand();
}
cout << "Sorting Array .......\n";
clock_t start = clock();
sortArray(values, x);
cout << "The Array Now Sorted\n";
printf("Elapsed Time : %f\n", ((double)clock() - start) / CLOCKS_PER_SEC);
cout << "\n";
}
void sortArray(int array[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (array[count] > array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = true;
}
}
}while (swap);
}
it takes now about 13 seconds i tried to put ##pragma omp parallel for before "for statment" in sortArray method and it didnt make any difference it take also about 13 second ..... so please help me as fast as you can
Try this Parallel Bubble Sort algorithm:
1. For k = 0 to n-2
2. If k is even then
3. for i = 0 to (n/2)-1 do in parallel
4. If A[2i] > A[2i+1] then
5. Exchange A[2i] ↔ A[2i+1]
6. Else
7. for i = 0 to (n/2)-2 do in parallel
8. If A[2i+1] > A[2i+2] then
9. Exchange A[2i+1] ↔ A[2i+2]
10. Next k
Parallel Analysis
Steps 1-10 is a one big loop that is represented n -1 times. Therefore, the parallel time complexity is O(n). If the algorithm, odd-numbered steps need (n/2) - 2 processors and even-numbered steps require
(n/2) - 1 processors.Therefore, this needs O(n) processors.
You can still use a swap flag check to stop the routine right before Next k.
Of course don't expect great speed improvement without hundreds of physical processors :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With