使用 MPI 在 C++ 中进行 BubbleSort
BubbleSort in c++ using MPI
我是 MPI 的初学者,正在尝试编写排序代码 (BubbleSort)
代码有效,但我好像遗漏了什么
代码在这里:--->
#define N 10`
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <stddef.h>
#include "mpi.h"
using namespace std;
int main(int argc, char* argv[])
{
int i, j, k, rank, size;
int a[N] = { 10,9,8,7,6,5,4,3,2,1 };
int c[N];
int aa[N], cc[N];
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Scatter(a, N/size, MPI_INT, aa, N/size , MPI_INT, 0, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
int n = N/size;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (aa[j] > aa[j + 1]) {
int temp = aa[j];
aa[j] = aa[j + 1];
aa[j + 1] = temp;
}
}
}
for (int i = 0; i < n; i++) {
cc[i] = aa[i];
};
MPI_Barrier(MPI_COMM_WORLD);
MPI_Gather(cc, N/size , MPI_INT, c, N/size, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
cout << cc[9];
if (rank == 0) {
cout << "C is look like : " << endl;
for (int i = 0; i < N; i++) {
cout << c[i] << " ";
}
}
}
程序输出:-->
最后我们得到错误
一般来说,我的 MPI 配置为 4 个处理器
-858993460 C is look like :
-858993460
-858993460
-858993460
9 10 7 8 5 6 3 4 -858993460 -858993460
你的程序有几个问题:
cc[9]
使用未初始化
- 你只对
(N/size)*size)
个元素进行操作,在你的情况下 N=10, size=4
,这意味着你只对 8 个元素进行操作。解决方法是使用 MPI_Scatterv()
和 MPI_Gatherv()
- 假设你的冒泡排序是正确的(我没有检查那部分),你的程序收集排序的(子)数组,你不能天真地期望结果是一个(全尺寸)排序数组。
我是 MPI 的初学者,正在尝试编写排序代码 (BubbleSort) 代码有效,但我好像遗漏了什么
代码在这里:--->
#define N 10`
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <stddef.h>
#include "mpi.h"
using namespace std;
int main(int argc, char* argv[])
{
int i, j, k, rank, size;
int a[N] = { 10,9,8,7,6,5,4,3,2,1 };
int c[N];
int aa[N], cc[N];
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Scatter(a, N/size, MPI_INT, aa, N/size , MPI_INT, 0, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
int n = N/size;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (aa[j] > aa[j + 1]) {
int temp = aa[j];
aa[j] = aa[j + 1];
aa[j + 1] = temp;
}
}
}
for (int i = 0; i < n; i++) {
cc[i] = aa[i];
};
MPI_Barrier(MPI_COMM_WORLD);
MPI_Gather(cc, N/size , MPI_INT, c, N/size, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
cout << cc[9];
if (rank == 0) {
cout << "C is look like : " << endl;
for (int i = 0; i < N; i++) {
cout << c[i] << " ";
}
}
}
程序输出:--> 最后我们得到错误 一般来说,我的 MPI 配置为 4 个处理器
-858993460 C is look like :
-858993460
-858993460
-858993460
9 10 7 8 5 6 3 4 -858993460 -858993460
你的程序有几个问题:
cc[9]
使用未初始化- 你只对
(N/size)*size)
个元素进行操作,在你的情况下N=10, size=4
,这意味着你只对 8 个元素进行操作。解决方法是使用MPI_Scatterv()
和MPI_Gatherv()
- 假设你的冒泡排序是正确的(我没有检查那部分),你的程序收集排序的(子)数组,你不能天真地期望结果是一个(全尺寸)排序数组。