Search code examples
c++mpibubble-sort

BubbleSort in c++ using MPI


I am a beginner in MPI and am trying to write sort code(BubbleSort) The code works, but it seems like I'm missing something

Code is here:--->

#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] << "   ";

        }
    }
}

Output of the program:--> In the end we get errors In general, my MPI is configured as 4 processors

-858993460 C is look like :
-858993460
-858993460
-858993460
9   10   7   8   5   6   3   4   -858993460   -858993460

Solution

  • There are several issues in your program :

    • cc[9] is used uninitialized
    • you only operate on (N/size)*size) elements, and in your case N=10, size=4, it means you operate on only 8 elements. The cure is to use MPI_Scatterv() and MPI_Gatherv()
    • assuming your bubble sort is correct (I did not check that part), your program gathers sorted (sub)arrays, and you cannot naively expect the outcome is a (full size) sorted array.