#include<stdio.h>
#include<time.h>
#include<string.h>
#include<stdlib.h>
#include "mpi.h"
int cmp(const void *a,const void *b)
{
return *(int*)a-*(int*)b;
}
int main(int argc,char **argv)
{
MPI_Init(&argc,&argv);
int rank,size;
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
int n=atoi(argv[1]);
int i;
int *buf=NULL;
int *cnts=NULL;
int *ofss=NULL;
int *revbuf=NULL;
int block=(n+size-1)/size;
int ofs=rank*block;
if((rank+1)*block>=n) block=n-rank*block;
revbuf=(int*)malloc(n*sizeof(int));
memset(revbuf,-1,n*sizeof(int));
if(rank==0)
{
buf=(int*)malloc(n*sizeof(int));
cnts=(int*)malloc(size*sizeof(int));
ofss=(int*)malloc(size*sizeof(int));
int *var=(int*)malloc(n*sizeof(int));
srand((int)time(0));
for(i=0;i<n;++i)
{
buf[i]=(int)rand()%n;
var[i]=buf[i];
// printf("%d\t",buf[i]);
}
//printf("\n");
qsort(var,n,sizeof(int),cmp);
for(i=0;i<n;++i)
printf("%d\t",var[i]);
printf("\n");
int j=0;
while(j*block<n)
{
cnts[j]=block<n-j*block?block:n-j*block;
ofss[j]=j*block;
++j;
}
}
MPI_Scatterv(buf,cnts,ofss,MPI_INT,revbuf,block,MPI_INT,0,MPI_COMM_WORLD);
qsort(revbuf,block,sizeof(int),cmp);
int mod=2;
int loop=1;
MPI_Status st;
int sz=size;
while(sz>1)
{
if(rank%mod==0 && rank+(mod>>1)<size)
{
MPI_Recv(revbuf+block,n-block,MPI_INT,rank+(mod>>1),loop,MPI_COMM_WORLD,&st);
int *tmpbuf=(int*)malloc(n*sizeof(int));
i=0;
int j=block;
int idx=0;
while(i<block && j<n && revbuf[j]!=-1)
{
if(revbuf[i]<=revbuf[j])
tmpbuf[idx++]=revbuf[i++];
else
tmpbuf[idx++]=revbuf[j++];
}
while(i<block)
tmpbuf[idx++]=revbuf[i++];
while(j<n && revbuf[j]!=-1)
tmpbuf[idx++]=revbuf[j++];
for(i=0;i<idx;++i)
revbuf[i]=tmpbuf[i];
block=idx;
free(tmpbuf);
}
else if(rank%mod==(mod>>1))
{
MPI_Send(revbuf,block,MPI_INT,rank-(mod>>1),loop,MPI_COMM_WORLD);
free(revbuf);
break;
}
mod<<=1;
++loop;
sz=(sz+1)/2;
}
if(rank==0)
{
for(i=0;i<n;++i)
printf("%d\t",revbuf[i]);
printf("\n");
free(buf);
free(cnts);
free(ofss);
free(revbuf);
}
MPI_Finalize();
return 0;
}
MPI——归并排序
最新推荐文章于 2023-08-17 22:40:21 发布