其他分享
首页 > 其他分享> > c – 使用openmp进行并行冒泡排序

c – 使用openmp进行并行冒泡排序

作者:互联网

我写了一个用于冒泡排序算法的c代码,我不知道如何使用openmp使其并行,所以请帮助我…..
这是代码:

#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);
}

我现在需要花费大约13秒才能完成
     ## pragma omp parallel for
在sortArray方法中的“for statment”之前它并没有任何区别它也需要大约13秒…..
所以请尽快帮助我

解决方法:

试试这个Parallel Bubble Sort算法:

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.

您仍然可以使用交换标志检查在Next k之前停止例行程序.
当然不要指望没有数百个物理处理器的速度提升:)

标签:bubble-sort,c,parallel-processing
来源: https://codeday.me/bug/20190827/1741965.html