我写了一个顺序归并排序程序,如下所示:
#include "stdafx.h"
#include "iostream"
#include "omp.h"
#include "fstream"
using namespace std;
int a[50];
void merge(int,int,int);
void merge_sort(int low,int high)
{
int mid,newval;
double clock, clock1,clock2;
if(low<high)
{
mid=(low+high)/2;
#pragma omp parallel shared(low,mid,high) num_threads(2)
{
//newval=omp_get_thread_num();
//cout<<"thread: "<<newval<<endl;
merge_sort(low,mid);
clock=omp_get_wtime();
//cout<<"Clock: "<<clock<<endl;
merge_sort(mid+1,high);
merge(low,mid,high);
clock1=omp_get_wtime();
//cout<<"Clock1: "<<clock<<endl;
clock2=clock1-clock;
cout<<"Clock2: "<<clock2<<endl;
}
//cout<<"valud=%d"<<low<<endl;
}
}
void merge(int low,int mid,int high)
{
int h,i,j,b[50],k;
h=low;
i=low;
j=mid+1;
while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
}
i++;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++) a[k]=b[k];
}
void main()
{
int num,i;
int clock_n,len;
FILE *fp;
char *buf;
char *newchat;//ifstream properfile;
cout<<"********************************************************************************"<<endl;
cout<<" MERGE SORT PROGRAM"<<endl;
cout<<"********************************************************************************"<<endl;
cout<<endl<<endl;
cout<<"Please Enter THE NUMBER OF ELEMENTS you want to sort [THEN PRESS ENTER]:"<<endl;
cout<<endl;
//cout<<"Now, Please Enter the ( "<< num <<" ) numbers (ELEMENTS) [THEN PRESS ENTER]:"<<endl;
//for(i=1;i<=num;i++)
//{
fp=fopen("E:\\Study\\Semester 2\\Compsci 711- Parallel and distributed computing\\Assignment\\sample_10.txt","rb");
fseek(fp,0,SEEK_END); //go to end
len=ftell(fp); //get position at end (length)
cout<<"Length is %d"<<len<<endl;
//fseek(fp,0,SEEK_SET); //go to beg.
buf=(char *)malloc(len); //malloc buffer
newchat=buf;
fread(newchat,len,1,fp); //read into buffer
fclose(fp);
//cout<<"Read %c"<<newchat<<endl;
////cin>>num;
//}
merge_sort(1,len);
cout<<endl;
cout<<"So, the sorted list (using MERGE SORT) will be :"<<endl;
cout<<endl<<endl;
for(i=1;i<=num;i++)
cout<<a[i]<<" ";
cout<<endl<<endl<<endl<<endl;
}现在我想并行化这段代码(C中用于并行化的API是OPENMP)。你能帮我摆脱困境吗?基本上,我使用了#杂注并行num_thread(4),但我不知道是否应该包含其他内容才能进行并行化。
发布于 2012-08-14 17:57:29
合并排序算法的主要瓶颈是合并功能。其复杂度为O(n)。前几个合并操作的成本将主导整个应用程序的成本。对较大的数组使用优化的并行算法。
对于较小的数组(<20个元素),请避开障碍。实际上,我更喜欢顺序O(n^2)算法。
您不应该使用sections而不是#pragma omp parallel shared(low,mid,high) num_threads(2)吗
发布于 2013-04-22 21:10:31
如果排序小于128个32位整数(适合cpu缓存),那么二进制插入排序通常是最好的。
如果对较大的数字进行排序,下面的文章将介绍如何进行并行合并排序。
http://www1.chapman.edu/~radenski/research/papers/mergesort-pdpta11.pdf
这篇文章介绍了OMP和MPI上的并行拆分,但没有解释如何并行合并
http://www.cc.gatech.edu/~ogreen3/_docs/Merge_Path_-_Parallel_Merging_Made_Simple.pdf
本文解释了如何在parralel中进行合并。尽管它的名字一开始让我很困惑,但归根结底,当对两个已排序的列表进行排序时,秩排序(普通的合并方法)要么向下(向上数组A),要么向下(向上数组B)合并矩阵,这就是所谓的合并路径。如果使用多个处理器,您可以拆分区域,并通过使用对角线和二进制搜索找到合并路径,在任何点进行排名排序。
https://stackoverflow.com/questions/11944457
复制相似问题