Ladies_Man

#SORT__Merge & Insert (Слияние - Вставки)

Dec 17th, 2013
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.41 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int *array;
  5. int *temp;
  6. int n;
  7.  
  8. void merge(int first, int last)
  9. {
  10.     int i, j, k = 0, dummy, mid = (first + last)/2, first_new = first, last_new = last;
  11.  
  12.     if ((first - last + 1) < 6) {
  13.         for (i = 1; i <= last; i++) {
  14.             j = i;
  15.             while ((j > 0) && ((abs(array[j])) < (abs(array[j-1])))) {
  16.                 dummy = array[j];
  17.                 array[j] = array[j - 1];
  18.                 array[j - 1] = dummy;
  19.                 j--;
  20.             }
  21.         }
  22.         return;
  23.     }
  24.  
  25.     temp = (int*)malloc(n * sizeof(int));
  26.     merge(first, mid);
  27.     merge(mid + 1, last);
  28.  
  29.     while (last - first + 1 != k) {
  30.         if (first_new > mid)
  31.             temp[k++] = array[last_new++];
  32.         else
  33.             if (last_new > last)
  34.                 temp[k++] = array[first_new++];
  35.             else
  36.                 if (abs(array[first_new]) > abs(array[last_new]))
  37.                     temp[k++] = array[last_new++];
  38.                 else
  39.                     temp[k++] = array[first_new++];
  40.     }
  41.  
  42.     for (i = 0; i < k; i++)
  43.         array[first + i] = temp[i];
  44. }
  45.  
  46. int main()
  47. {
  48.     int i, n;
  49.     scanf("%d", &n);
  50.  
  51.     array = (int*)malloc(n * sizeof(int));
  52.     for (i = 0; i < n; i++) scanf("%d", array + i);
  53.  
  54.     merge(0, n-1);
  55.  
  56.     for (i = 0; i < n; i++) printf("%d ", array[i]);
  57.  
  58.     free(array);
  59.     free(temp);
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment