Skip to content
Snippets Groups Projects
Commit cee39bd4 authored by Muhtar Hartopo's avatar Muhtar Hartopo
Browse files

bucket sort

parent 729bc0e6
No related merge requests found
bucket.c 0 → 100644
#include <omp.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <assert.h>
// Creates an array of random numbers. Each number has a value from 0 - 1
int *create_rand_nums(int num_elements);
//insertion sort
void insert_sort(int *data, int size);
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "Usage: num_elements\n");
exit(1);
}
int num_thread;
int num_elements = atoi(argv[1]);
// Seed the random number generator to get different results each time
srand(time(NULL));
int * data = create_rand_nums(num_elements);
int **bucket;
int min = 0;
int max = num_elements;
int num_range;
int *last_idx;
#pragma omp parallel
{
int nthrds = omp_get_num_threads();
int id = omp_get_thread_num();
if(id == 0) {
num_thread = nthrds;
num_range = (max -min)/nthrds;
last_idx = (int *)malloc(sizeof(int) * nthrds);
int i;
for(i = 0; i < nthrds; i++) {
last_idx[i] = 0;
}
bucket = (int **) malloc(sizeof(int*) * num_thread);
for(i = 0; i < num_thread; i++) {
bucket[i] = (int *) malloc (sizeof(int) * num_elements);
}
}
#pragma omp barrier
int i;
for(i = id; i < num_elements; i += nthrds) {
int dest = data[i]/num_range;
bucket[dest][last_idx[id]] = data[i];
last_idx[id]++;
}
#pragma omp barrier
insert_sort(bucket[id],last_idx[id]);
}
int i,j;
int k = 0;
for(i = 0; i< num_thread; i++) {
for(j = 0; j < last_idx[i]; j++) {
data[k] = bucket[i][j];
k++;
}
}
for(i =0; i < num_elements; i++) {
printf("%d - ",data[i]);
}
free(data);
free(last_idx);
for(i = 0; i< num_thread; i++) {
free(bucket[i]);
}
free(bucket);
return 0;
}
// Creates an array of random numbers. Each number has a value from 0 - 1
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() % num_elements);
}
return rand_nums;
}
//insertion sort
void insert_sort(int *data, int size) {
int i,j,t;
for (i = 1 ; i < size; i++) {
j = i;
while ( j > 0 && data[j] < data[j-1]) {
t = data[j];
data[j] = data[j-1];
data[j-1] = t;
j--;
}
}
}
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