diff --git a/bucket_sort b/bucket_sort new file mode 100755 index 0000000000000000000000000000000000000000..ba6e36936b16ffb9602c03cc83bae53725e60764 Binary files /dev/null and b/bucket_sort differ diff --git a/bucket_sort_omp.c b/bucket_sort_omp.c new file mode 100644 index 0000000000000000000000000000000000000000..1967e72f4aba07e5c51531c94836e6dae00fad9a --- /dev/null +++ b/bucket_sort_omp.c @@ -0,0 +1,107 @@ +//Nama File : bucket_sort_omp.c +//Oleh : Jessica Handayani 13513069 & Asanilta Fahda 13513079 + + +#include <omp.h> +#include <stdio.h> +#include <stdlib.h> +#include <time.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)num_elements); + } + return rand_nums; +} + +int** create_bucket_arrays(int num_buckets, int num_elements) { + int i; + int** bucket_arrays = (int**)malloc(sizeof(int*) * num_buckets); + for (i = 0; i < num_buckets; i++) { + bucket_arrays[i] = (int *)malloc(sizeof(int) * num_elements); + } + return bucket_arrays; +} + +int* insertion_sort(int* elements, int num_elements){ + int i,j; + int temp; + for(i = 0; i < num_elements; i++){ + j = i; + while (j > 0 && elements[j] < elements[j-1]) { + temp = elements[j]; + elements[j] = elements[j-1]; + elements[j-1] = temp; + + j--; + } + } + + return elements; + +} + +int main(int argc, char* argv[]) { + if (argc != 2){ + fprintf(stderr, "Usage: num_elements\n"); + exit(1); + } + + double time = 0.0; + int thread_count = strtol(argv[1], NULL, 10); + int N; + printf("Enter N\n"); + scanf("%d", &N); + int i; + int j; + + //create array of N random numbers + int* rand_nums = create_rand_nums(N); + int** bucket_arrays = create_bucket_arrays(thread_count,N); + int* last_index = (int *)malloc(sizeof(int) * thread_count); + + for (i = 0; i < thread_count; i ++) { + last_index[i] = 0; + } + + int bucket_range = (N%thread_count == 0) ? N/thread_count : N/thread_count+1; + + time -= omp_get_wtime(); + + int bucket; + //insert numbers to appropriate bucket arrays + for (i = 0; i < N; i++) { + bucket = rand_nums[i]/bucket_range; + bucket_arrays[bucket][last_index[bucket]++] = rand_nums[i]; + } + + + //sort arrays in parallel + # pragma omp parallel for num_threads(thread_count) + for (i = 0; i < thread_count; i++) { + bucket_arrays[i] = insertion_sort(bucket_arrays[i],last_index[i]); + } + + + //combine sorted arrays + int* sorted_array = (int *)malloc(sizeof(int) * N); + int last_sorted_index = 0; + for (i = 0; i < thread_count; i++) { + for (j = 0; j < last_index[i]; j++) { + sorted_array[last_sorted_index++] = bucket_arrays[i][j]; + } + } + time += omp_get_wtime(); + printf("Sorted: "); + for (i = 0; i < N; i++) { + printf("%d ",sorted_array[i]); + } + printf("\nTime : %lf s\n", time); + + +} +