Skip to content
Snippets Groups Projects
Commit 92a0d508 authored by 13513096's avatar 13513096
Browse files

Complete Task

parent fb28200d
Branches master
No related merge requests found
File added
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <assert.h>
#include <unistd.h>
#include <time.h>
int* create_random(int num) {
int* ret = (int*) malloc(sizeof(int) * num);
int i;
for(i = 0; i < num; i++) {
ret[i] = rand() % 100000;
}
return ret;
}
int sum_cumm(int* a, int n) {
int i;
int sum = 0;
for (i = 0; i < n; ++i)
{
sum += a[i];
}
return sum;
}
void quick_sort(int *a,int low,int high)
{
int pivot,j,temp,i;
if(low<high) {
pivot = low;
i = low;
j = high;
while(i<j) {
while((a[i]<=a[pivot])&&(i<high)) {
i++;
}
while(a[j]>a[pivot]) {
j--;
}
if(i<j) {
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
quick_sort(a,low,j-1);
quick_sort(a,j+1,high);
}
}
void sort(int* a, int k, int l) {
int i, j, t;
for(i = k; i < l; i++) {
for(j = i + 1; j < l; j++) {
if(a[i] > a[j]) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
}
int main(int argc, char** argv) {
if(argc != 3) {
fprintf(stderr, "Usage: thread_count num_elements");
return 0;
}
int thread_count = atoi(argv[1]);
int n = atoi(argv[2]);
int* num_bucket = (int*) malloc(sizeof(int) * thread_count);
int i, j;
int* a = create_random(n);
printf("Done randomized\n");
int mn = 2000000000;
int mk = -2000000000;
for(i = 0; i < n; i++) {
if(a[i] > mk) mk = a[i];
if(a[i] < mn) mn = a[i];
}
int range = mk - mn;
int leap = range / thread_count + 1;
int* this = (int*) malloc(sizeof(int) * n);
int* cur = (int*) malloc(sizeof(int) * n);
for(i = 0; i < thread_count; i++) num_bucket[i] = 0;
int cur_pos = 0;
for(j = 0; j < thread_count; j++) {
for(i = 0; i < n; i++) {
if(mn + j*leap <= a[i] && a[i] < mn + (j + 1)*leap) {
cur[num_bucket[j]+cur_pos] = a[i];
num_bucket[j]++;
}
}
cur_pos += num_bucket[j];
}
clock_t begin = clock();
# pragma omp parallel for num_threads(thread_count)
for (i = 0; i <= thread_count; i++)
{
if (i == 0)
{
quick_sort(cur,0,num_bucket[i]-1);
}
else {
quick_sort(cur,sum_cumm(num_bucket,i-1),sum_cumm(num_bucket,i)-1);
}
}
clock_t end = clock();
printf("Running time (ms) : %lf\n", (double)(end - begin) *1000 / CLOCKS_PER_SEC);
return 0;
}
test 0 → 100755
File added
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