Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <sys/types.h>
- #define MAXN 100005
- #define THMAX 5
- #define min(x, y) (x <= y ? x : y)
- int arr[MAXN];
- pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
- int flag = 0;
- int stack[THMAX], top;
- typedef struct{
- int a, b, x, y, idx;
- }merge_range;
- void* merge(void* data){
- //pthread_mutex_lock(&mtx);
- merge_range *args = data;
- int l = args-> a, r = args->b, i = args->x, j = args->y;
- int val = args -> idx;
- //pthread_mutex_unlock(&mtx);
- //printf("%d %d to %d %d\n", l, r, i, j);
- int x = l, y = j;
- int k, ord[MAXN];
- for(k = l; l <= r && i <= j; k++){
- if(arr[l] <= arr[i]) ord[k] = arr[l++];
- else ord[k] = arr[i++];
- }
- while(l <= r) ord[k++] = arr[l++];
- while(i <= j) ord[k++] = arr[i++];
- for(; x <= y; x++) arr[x] = ord[x];
- pthread_mutex_lock(&mtx);
- stack[++top] = val;
- pthread_mutex_unlock(&mtx);
- return NULL;
- }
- void merge_sort(int n){
- int i, j, qtd = 0, aux;
- pthread_t thr[THMAX];
- merge_range tmp[THMAX];
- for(i = 0; i < THMAX; i++) stack[i] = i;
- top = THMAX - 1;
- for(i = 1; i <= n; i <<= 1){
- for(j = 0; j + i <= n; j += (i << 1) ){
- while(top < 0);
- aux = stack[top];
- tmp[ aux ].a = j; tmp[ aux ].b = j + i - 1;
- tmp[ aux ].x = min(tmp[ aux ].b + 1, n - 1); tmp[aux].y = min(tmp[aux].x + i - 1, n - 1);
- tmp[aux].idx = stack[aux];
- pthread_create( &thr[ aux ], NULL, &merge, &tmp[aux]);
- pthread_join(thr[ stack[top--] ], NULL);
- }
- while(top != THMAX - 1);
- }
- }
- int main(){
- freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- int n;
- scanf("%d", &n);
- int i;
- for(i = 0; i < n; i++){
- scanf("%d", arr + i);
- }
- merge_sort(n);
- for(i = 0; i < n; i++){
- printf("%d ", arr[i]);
- }
- putchar('\n');
- }
Advertisement
Add Comment
Please, Sign In to add comment