diff --git a/bucketSort.c b/bucketSort.c new file mode 100644 index 0000000000000000000000000000000000000000..9ae4918045b6434053168462c2e6fb1242102807 --- /dev/null +++ b/bucketSort.c @@ -0,0 +1,89 @@ +// Copyright 2012 www.mpitutorial.com +// Program yang menghitung rataÂrata dari array secara paralel menggunakan Scatter dan Gather. +#include <stdio.h> +#include <stdlib.h> +#include <time.h> +#include <mpi.h> +#include <assert.h> + +float *create_rand_nums(int num_elements, int num_per_bucket) { + float *rand_nums = (float *)malloc(sizeof(float) * num_elements); + assert(rand_nums != NULL); + int i; + for (i = 0; i < num_elements; i++) { + rand_nums[i] = ((rand() % (float)RAND_MAX) % (float)(i/num_per_bucket) * 200) + (float)(i/num_per_bucket) * 200; + } + return rand_nums; +} + +float * bucketSort(float *array, int n) { + 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--; + } + } + return array; +} + +int main(int argc, char** argv) { + if (argc != 2) { + fprintf(stderr, "Usage: avg num_elements_per_proc\n"); + exit(1); + } + + int num_elements_per_proc = 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); + + float *rand_nums = NULL; + if (world_rank == 0) { + rand_nums = create_rand_nums(num_elements_per_proc * world_size); + } + + float *sub_rand_nums = (float *)malloc(sizeof(float) * + num_elements_per_proc); + assert(sub_rand_nums != NULL); + + + MPI_Scatter(rand_nums, num_elements_per_proc, MPI_FLOAT, sub_rand_nums, + num_elements_per_proc, MPI_FLOAT, 0, MPI_COMM_WORLD); + + float* sub_bucket = bucketSort(sub_rand_nums, num_elements_per_proc); + + float *sub_buckets = NULL; + if (world_rank == 0) { + sub_buckets = (float *)malloc(sizeof(float) * world_size); + assert(sub_buckets != NULL); + } + MPI_Gather(&sub_bucket, num_elements_per_proc, MPI_FLOAT, sub_buckets, 1, MPI_FLOAT, 0, + MPI_COMM_WORLD); + + if (world_rank == 0) { + int i; + for(i=0; i<(num_elements_per_proc*world_size); i++) + printf("Avg of all elements is %f\n",sub_buckets[i]); + } + + if (world_rank == 0) { + free(rand_nums); + free(sub_bukcets); + } + free(sub_rand_nums); + + MPI_Barrier(MPI_COMM_WORLD); + MPI_Finalize(); +} + +