diff --git a/bucketsort b/bucketsort new file mode 100755 index 0000000000000000000000000000000000000000..1dc7a56976e86137a387007ea2ce810e505779d3 Binary files /dev/null and b/bucketsort differ diff --git a/bucketsort.c b/bucketsort.c new file mode 100644 index 0000000000000000000000000000000000000000..6cc3cb550138abfac71d49a8946b80e9bf73a9b3 --- /dev/null +++ b/bucketsort.c @@ -0,0 +1,107 @@ +#include <stdio.h> +#include <stdlib.h> +#include <time.h> +#include <mpi.h> +#include <assert.h> + +float *create_rand_nums(int num_elements) { + 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); + } + return rand_nums; +} + +float compute_avg(float *array, int num_elements) { + float sum = 0.f; + int i; + for (i = 0; i < num_elements; i++) { + sum += array[i]; + } + return sum / num_elements; +} + +int main(int argc, char** argv) { + if (argc != 2) { + fprintf(stderr, "Usage: avg num_elements_per_proc\n"); + exit(1); + } + MPI_Status Stat; + + 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); + int i, j, rc; + float inmsg[range]; + + float *rand_nums = NULL; + if (world_rank == 0) { + rand_nums = create_rand_nums(num_elements_per_proc * world_size); + int range = (RAND_MAX)/world_size; + float bucket[range]; + int k; + for (i = 0; i < world_size; i++) { + k = 0; + for (j = 0; j < num_elements_per_proc * world_size; j++) { + if ((rand_nums[j] < i*range+range) && (rand_nums[j] => i*range)) { + bucket[k] = rand_nums[j]; + k++; + } + } + rc = MPI_Send(bucket, range, MPI_FLOAT, i, 1, MPI_COMM_WORLD); + } + + } + rc = MPI_Recv(inmsg, range, MPI_FLOAT, 0, 1, MPI_COMM_WORLD, &Stat); + float t; + for (i = 1 ; i <= range - 1; i++) { + j = i; + + while ( j > 0 && inmsg[j] < inmsg[j-1]) { + t = inmsg[j]; + inmsg[j] = inmsg[j-1]; + inmsg[j-1] = t; + + j--; + } + } + rc = MPI_Send(bucket, range, MPI_FLOAT, 0, 1, MPI_COMM_WORLD); + + if (world_rank == 0) { + sub_avgs = (float *)malloc(sizeof(float) * world_size); + assert(sub_avgs != NULL); + } + MPI_Gather(&sub_avg, 1, MPI_FLOAT, sub_avgs, 1, MPI_FLOAT, 0, MPI_COMM_WORLD); + + if (world_rank == 0) { + k = 0; + for (i = 0; i < world_size; i++) { + rc = MPI_Recv(bucket, range, MPI_FLOAT, i, 1, MPI_COMM_WORLD, &Stat); + for (j = 0; j < range; j++) { + if (bucket[j] >= 0) { + rand_num[k] = bucket[j]; + k++; + } + } + + } + } + + if (world_rank == 0) { + free(rand_nums); + free(sub_avgs); + } + free(sub_rand_nums); + + MPI_Barrier(MPI_COMM_WORLD); + MPI_Finalize(); +} +