Skip to content
Snippets Groups Projects
Commit dbfd8131 authored by 13513004's avatar 13513004
Browse files

mergesort cluster

parent a4350684
No related merge requests found
#include <stdlib.h>
#include <mpi.h>
#include <stdio.h>
void merge(int* arr, int l, int m, int r, int* tmp)
{
......@@ -34,15 +36,59 @@ void mergesort(int* arr, int l, int r, int* tmp)
merge(arr, l, m, r, tmp);
}
int main(int argc, char const *argv[])
int main(int argc, char *argv[])
{
int x[] = {3, 5, 2, 6,8, 9, 1,0};
int* tmp = (int*) malloc(sizeof(int) * 8);
mergesort(x, 0, 8, tmp);
for (int i = 0; i < 8; ++i)
int n, i;
scanf("%d", &n);
int *arr = (int*) malloc(sizeof(int) * (n + 1));
for (i = 0; i < 8; ++i)
{
printf("%d ", x[i]);
scanf("%d", &arr[i]);
}
if (tmp != NULL) free(tmp);
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);
int size = n / world_size; // equally distributed
int *arr_part = (int*) malloc(sizeof(int) * size);
MPI_Scatter(arr, size, MPI_INT, arr_part, size, MPI_INT, 0, MPI_COMM_WORLD); // scatter to buckets
int *tmp = (int*) malloc(sizeof(int) * size);
mergesort(arr_part, 0, size, tmp);
int *sorted = NULL;
if(world_rank == 0) {
sorted = malloc(n * sizeof(int));
}
MPI_Gather(arr_part, size, MPI_INT, sorted, size, MPI_INT, 0, MPI_COMM_WORLD); // gather result
if(world_rank == 0)
{
int *tmp2 = (int*) malloc(sizeof(int) * n);
mergesort(sorted, 0, n, tmp2);
for(i = 0; i < n; i++)
{
printf("%d ", sorted[i]);
}
free(sorted);
free(tmp2);
}
free(arr);
free(arr_part);
free(tmp);
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
return 0;
}
\ No newline at end of file
sort 0 → 100755
File added
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment