【发布时间】:2021-02-17 13:49:17
【问题描述】:
我的程序正在对数组进行排序并且工作正常,但我只有一个小问题,它打印未排序的数组超过 1 次(取决于我选择了多少进程,如果我选择 2,它会打印两次)。我只想打印一次未排序的数组。有没有办法做到这一点?感谢您的帮助:)。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <mpi.h>
void merge(int*, int*, int, int, int);
void mergeSort(int*, int*, int, int);
int main(int argc, char** argv) {
/********** Create and populate the array **********/
int n = atoi(argv[1]);
int* original_array{ new int[n] {} };
//int original_array[]=new int[n];
int c;
srand(time(NULL));
printf("This is the unsorted array: ");
for (c = 0; c < n; c++) {
original_array[c] = rand() % n;
printf("%d ", original_array[c]);
}
printf("\n");
printf("\n");
/********** Initialize MPI **********/
int world_rank;
int world_size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
/********** Divide the array in equal-sized chunks **********/
int size = n / world_size;
/********** Send each subarray to each process **********/
int* sub_array{ new int[size] {} };
MPI_Scatter(original_array, size, MPI_INT, sub_array, size, MPI_INT, 0, MPI_COMM_WORLD);
/********** Perform the mergesort on each process **********/
int* tmp_array{ new int[size] {} };
mergeSort(sub_array, tmp_array, 0, (size - 1));
/********** Gather the sorted subarrays into one **********/
int* sorted = NULL;
if (world_rank == 0) {
sorted={ new int[n] {} } ;
}
MPI_Gather(sub_array, size, MPI_INT, sorted, size, MPI_INT, 0, MPI_COMM_WORLD);
/********** Povik na posledniot mergeSort call **********/
if (world_rank == 0) {
printf("Array state before final mergeSort call: ");
for (c = 0; c < n; c++) {
printf("%d ", sorted[c]);
}
printf("\n");
int* other_array{ new int[n] {} };
mergeSort(sorted, other_array, 0, (n - 1));
/********** Pecati sortirana niza **********/
printf("This is the sorted array: ");
for (c = 0; c < n; c++) {
printf("%d ", sorted[c]);
}
printf("\n");
printf("\n");
/********** Oslobodi memorija **********/
delete[] sorted;
delete[] other_array;
}
/********** Oslobodi memorija **********/
delete[] original_array;
delete[] sub_array;
delete[] tmp_array;
/********** Finalize MPI **********/
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
}
【问题讨论】:
标签: c++ performance parallel-processing mpi hpc