title: Sorting array with MPI in C++
body: <p>I want to sort array of random numbers using MPI library. The idea is to chop array with MPI_Scatterv and send it to the processes. Every process should localy sort its amount of data and send it back to the main process (MPI_Gatherv). Main process should sort partly sorted table(merge). If have problems with last step. I just cannot merge the table corectly.
  Any ideas? 
  Here is the code: </p>
  
  <pre><code>    #include &lt;malloc.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include "math.h"
  #include "mpi.h"
  #include &lt;time.h&gt;
  
  
  #define N 20
  
  int numOfProc, idproc;
  
  
  int compare(const void * a, const void * b) {
     const int *ia = (const int *)a;
      const int *ib = (const int *)b;
      return *ia  - *ib; 
  }
  
  
  
  int main(int argc,char ** argv) {
  
     MPI_Init(&amp;argc, &amp;argv);
     MPI_Comm_size(MPI_COMM_WORLD, &amp;numOfProc );
     MPI_Comm_rank(MPI_COMM_WORLD, &amp;idproc);
  
     int * buf, * send_buf, * receive_buf, * sorted_buf, *displ, *sendcnts, *recvcnts;
     int count = N/numOfProc;
     int size, i;
     int temp, index;
  
  
     displ=(int*)malloc(numOfProc*sizeof(int));
  
     sendcnts=(int*)malloc(numOfProc*sizeof(int));
  
     recvcnts=(int*)malloc(numOfProc*sizeof(int));
  
     buf=(int*)malloc(count*sizeof(int));
  
     for(i=0; i&lt;numOfProc; i++){
         displ[i]=i*count;
         sendcnts[i]=count;
         recvcnts[i]=count;
     }
  
  
  
     if(idproc == 0) {
        size=N;
        send_buf=(int*)malloc(size*sizeof(int));
        receive_buf=(int*)malloc(size*sizeof(int));
  
  
        for (i=0;i&lt;size;i++) {
           send_buf[i] = rand();
        }
        printf("\n\n");
        fflush(stdout);
     }
  
     MPI_Scatterv(send_buf, sendcnts, displ, MPI_INT, buf, count, MPI_INT, 0, MPI_COMM_WORLD);
  
     printf("proces %d: ", idproc);
     qsort(buf, count, sizeof(int), compare);
     for (int i = 0; i &lt; count; i++) printf("%d ", buf[i]);
     printf("\n\n");
     fflush(stdout);
  
     MPI_Gatherv(buf, count, MPI_INT, receive_buf, recvcnts, displ, MPI_INT, 0, MPI_COMM_WORLD);
  
     if (idproc == 0) {
         //merge
         temp=INT_MAX;
         for(i=0; i&lt;size; i++){
             for(int j=0; j&lt;numOfProc; j++){
  
                 if(temp&gt;receive_buf[displ[j]]){
                     temp=receive_buf[displ[j]];
                     receive_buf[displ[j]]=receive_buf[i];
                     receive_buf[i]=temp;
                 }
  
             }
  
             printf("%d ", receive_buf[i]);
         }
  
  
        printf("\n");
        fflush(stdout);
     }
     wait(100);
     MPI_Finalize();
  }
  </code></pre>
  
  <p>Thanks in advance, Igor</p>