From ee514bbaab1b3fd2c21fbf831de11a7fd53adb6f Mon Sep 17 00:00:00 2001 From: 13512054 <13512054@hpc.if.itb.ac.id> Date: Fri, 19 Feb 2016 11:21:47 +0700 Subject: [PATCH] belum selesai --- omp_bucket_sort.c | 87 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 omp_bucket_sort.c diff --git a/omp_bucket_sort.c b/omp_bucket_sort.c new file mode 100644 index 0000000..318495f --- /dev/null +++ b/omp_bucket_sort.c @@ -0,0 +1,87 @@ +#include <stdio.h> +#include <stdlib.h> +#include <omp.h> +#include <assert.h> +#include <string.h> +#include <time.h> + +void Hello(void); /* Thread function */ + +int *create_rand_nums(int num_elements, int* counts, int* displs, int num_buckets) { + int *rand_nums = (int *)malloc(sizeof(int) * num_elements); + assert(rand_nums != NULL); + srand(time(NULL)); + int bucket_size = RAND_MAX / num_buckets; + int i, j; + int** buckets; + buckets = (int **)malloc(sizeof(int*) * num_buckets); + for(i = 0; i < num_buckets; i++){ + counts[i] = 0; + displs[i] = 0; + buckets[i] = (int *)malloc(sizeof(int) * num_elements); + } + for (i = 0; i < num_elements; i++) { + int random = (rand() % RAND_MAX); + int bucket = random / bucket_size; + buckets[bucket][counts[bucket]] = random; + counts[bucket]++; + for(j = bucket+1; j < num_buckets; j++){ + displs[j]++; + } + } + for (i = 0; i < num_buckets; i++){ + memcpy(rand_nums + displs[i], buckets[i], counts[i]); + //printf("count %d\n", counts[i]); + free(buckets[i]); + } + free(buckets); + return rand_nums; +} + +void sort(int *array, int n) { + 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[]) { + int *array; + int *displacement; + int *count; + + int thread_count = strtol(argv[1], NULL, 10); + int num_element = strtol(argv[2], NULL, 10); + displacement = malloc(thread_count*sizeof(int)); + count = malloc(thread_count*sizeof(int)); + array = create_rand_nums(num_element, count, displacement, thread_count); +for(int i = 0; i < num_element; i++){ + printf("%d\n", array[i]); + } + + #pragma omp parallel for shared(array, displacement, count) num_threads(thread_count) + for(int i = 0; i < thread_count; i++) + { + + int my_rank = omp_get_thread_num(); + int thread_count = omp_get_num_threads(); + sort(array+displacement[i], count[i]); + } + for(int i = 0; i < num_element; i++){ + printf("%d\n", array[i]); + } +free(array); +free(displacement); +free(count); + return 0; +} + -- GitLab