Jeremiah_

SO P&T - 5

Sep 30th, 2018
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.06 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <pthread.h>
  5. #include <sys/types.h>
  6.  
  7. #define MAXN 100005
  8. #define THMAX 5
  9. #define min(x, y) (x <= y ? x : y)
  10.  
  11. int arr[MAXN];
  12. pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
  13. int flag = 0;
  14. int stack[THMAX], top;
  15.  
  16. typedef struct{
  17.     int a, b, x, y, idx;
  18. }merge_range;
  19.  
  20. void* merge(void* data){
  21.     //pthread_mutex_lock(&mtx);    
  22.     merge_range *args = data;
  23.     int l = args-> a, r = args->b, i = args->x, j = args->y;
  24.     int val = args -> idx;
  25.     //pthread_mutex_unlock(&mtx);
  26.     //printf("%d %d to %d %d\n", l, r, i, j);    
  27.     int x = l, y = j;
  28.     int k, ord[MAXN];
  29.     for(k = l; l <= r && i <= j; k++){
  30.         if(arr[l] <= arr[i]) ord[k] = arr[l++];
  31.         else ord[k] = arr[i++];
  32.     }
  33.     while(l <= r) ord[k++] = arr[l++];
  34.     while(i <= j) ord[k++] = arr[i++];
  35.     for(; x <= y; x++) arr[x] = ord[x];
  36.     pthread_mutex_lock(&mtx);
  37.     stack[++top] = val;
  38.     pthread_mutex_unlock(&mtx);
  39.     return NULL;
  40. }
  41.  
  42. void merge_sort(int n){
  43.     int i, j, qtd = 0, aux;
  44.     pthread_t thr[THMAX];
  45.     merge_range tmp[THMAX];
  46.  
  47.     for(i = 0; i < THMAX; i++) stack[i] = i;
  48.     top = THMAX - 1;
  49.  
  50.     for(i = 1; i <= n; i <<= 1){
  51.         for(j = 0; j + i <= n; j += (i << 1)  ){
  52.             while(top < 0);  
  53.             aux = stack[top];        
  54.             tmp[ aux ].a = j; tmp[ aux ].b = j + i - 1;
  55.             tmp[ aux ].x = min(tmp[ aux ].b + 1, n - 1); tmp[aux].y = min(tmp[aux].x + i - 1, n - 1);            
  56.             tmp[aux].idx = stack[aux];
  57.             pthread_create( &thr[ aux ], NULL, &merge, &tmp[aux]);
  58.             pthread_join(thr[ stack[top--] ], NULL);
  59.          }
  60.          while(top != THMAX - 1);
  61.     }
  62. }
  63.  
  64. int main(){
  65.     freopen("input.txt", "r", stdin);
  66.     freopen("output.txt", "w", stdout);
  67.  
  68.     int n;
  69.     scanf("%d", &n);
  70.    
  71.     int i;
  72.     for(i = 0; i < n; i++){
  73.         scanf("%d", arr + i);      
  74.     }      
  75.  
  76.     merge_sort(n);
  77.  
  78.     for(i = 0; i < n; i++){
  79.         printf("%d ", arr[i]);    
  80.     }
  81.     putchar('\n');
  82. }
Advertisement
Add Comment
Please, Sign In to add comment