#include #include #include int merge(double *ina, int lena, double *inb, int lenb, double *out) { int i,j; int outcount=0; for (i=0,j=0; i\n", la[n-1]); } void MPI_Pairwise_Exchange(int localn, double *locala, int sendrank, int recvrank, MPI_Comm comm) { /* * the sending rank just sends the data and waits for the results; * the receiving rank receives it, sorts the combined data, and returns * the correct half of the data. */ int rank; double remote[localn]; double all[2*localn]; const int mergetag = 1; const int sortedtag = 2; MPI_Comm_rank(comm, &rank); if (rank == sendrank) { MPI_Send(locala, localn, MPI_DOUBLE, recvrank, mergetag, MPI_COMM_WORLD); MPI_Recv(locala, localn, MPI_DOUBLE, recvrank, sortedtag, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } else { MPI_Recv(remote, localn, MPI_DOUBLE, sendrank, mergetag, MPI_COMM_WORLD, MPI_STATUS_IGNORE); merge(locala, localn, remote, localn, all); int theirstart = 0, mystart = localn; if (sendrank > rank) { theirstart = localn; mystart = 0; } MPI_Send(&(all[theirstart]), localn, MPI_DOUBLE, sendrank, sortedtag, MPI_COMM_WORLD); for (int i=mystart; i 0) { MPI_Pairwise_Exchange(n / size, local_a, rank - 1, rank, comm); } } printstat(rank, i-1, "after", local_a, n/size); // gather local_a to a MPI_Gather(local_a, n / size, MPI_DOUBLE, a, n / size, MPI_DOUBLE, root, comm); if (rank == root) printstat(rank, i, " all done ", a, n); return MPI_SUCCESS; } int main(int argc, char **argv) { MPI_Init(&argc, &argv); int n = argc-1; double a[n]; for (int i=0; i