Skip to content
Snippets Groups Projects
Commit 1cb88678 authored by 13513013's avatar 13513013
Browse files

Versi awal, not running yet

parent 51486e90
Branches
No related merge requests found
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <mpi.h>
#include <assert.h>
int *create_rand_nums(int num_elements) {
int *rand_nums = (int *)malloc(sizeof(int) * num_elements);
assert(rand_nums != NULL);
int i;
for (i = 0; i < num_elements; i++) {
rand_nums[i] = (rand() / (int)RAND_MAX);
}
return rand_nums;
}
void sort(int n, int* array[]) {
int c, d, t;
for (c = 1 ; c <= n - 1; c++) {
d = c;
while ( d > 0 && array[d] < array[d-1]) {
t = array[d];
array[d] = array[d-1];
array[d-1] = t;
d--;
}
}
}
int main(int argc, char** argv) {
MPI_Status stat;
int* bucky;
if (argc != 2) {
fprintf(stderr, "Usage: avg num_elements_per_proc\n");
exit(1);
}
int num_elements = atoi(argv[1]);
srand(time(NULL));
MPI_Init(NULL, NULL);
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
int *rand_nums = NULL;
int range = 0;
int bucket_loc = 0;
int rand_num = 0;
int buckets[world_size][num_elements];
int bucket_count[world_size];
if (world_rank == 0) {
rand_nums = create_rand_nums(num_elements-1);
range = num_elements/world_size;
for (int i=0; i < world_size; i++) {
bucket_count[i] = 0;
}
for (int i=0; i < sizeof(rand_nums); i++) {
rand_num = rand_nums[i];
bucket_loc = rand_num/range;
buckets[bucket_loc][bucket_count[bucket_loc]] = rand_num;
bucket_count[bucket_loc]++;
}
for (int i=1; i < world_size; i++) {
MPI_Send(&buckets[i],bucket_count[i],MPI_INT, i, 1, MPI_COMM_WORLD);
}
} else {
MPI_Recv(&bucky, bucket_count[world_rank], MPI_INT, 0, 1, MPI_COMM_WORLD, &stat);
sort(sizeof(bucky), &bucky);
}
MPI_Gather(&bucky, sizeof(bucky), MPI_INT, buckets[world_rank], sizeof(bucky), MPI_INT, 0, MPI_COMM_WORLD);
printf("Sorted list in ascending order:\n");
for (int c = 0; c < world_size; c++) {
for (int d = 0; d < bucket_count[c]; d++) {
printf("%d\n", buckets[c][d]);
}
}
MPI_Finalize();
}
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