我编写了一个顺序合并排序程序,如下所示:
#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)。你能帮帮我吗?基本上我使用#pragma parallel num_thread(4) 但我不知道我是否应该包含其他任何内容以进行并行化。