Advertisement
runewalsh

Жду обещанную фотку

Nov 13th, 2015
1,006
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.67 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <assert.h>
  4. #include <stdbool.h>
  5. #include <string.h>
  6. #define cast(type, expr) (type)(expr)
  7. #define array_size(arr) (sizeof(arr) / sizeof(arr[0]))
  8.  
  9. typedef unsigned int uint;
  10. typedef int elem_t;
  11.  
  12. void* checked_malloc(size_t size, const char* for_what)
  13. {
  14.     void* ptr = malloc(size);
  15.     if (!ptr)
  16.     {
  17.         fprintf(stderr, "Memory allocation for %s failed", for_what);
  18.         exit(1);
  19.     }
  20.     return ptr;
  21. }
  22.  
  23. void _msort(uint n, elem_t* src, elem_t* dst, bool inplace)
  24. {
  25.     assert(n != 0);
  26.     if (n == 1)
  27.     {
  28.         if (!inplace) dst[0] = src[0];
  29.         return;
  30.     }
  31.  
  32.     uint avg = n/2;
  33.     uint nL = avg, nR = n - avg;
  34.     _msort(nL, src, dst, !inplace);
  35.     _msort(nR, src + avg, dst + avg, !inplace);
  36.  
  37.     elem_t* tmp = inplace ? dst : src;
  38.     elem_t* target = inplace ? src : dst;
  39.     elem_t* L = tmp, *R = tmp + nL;
  40.     for (; nL && nR; target++)
  41.     {
  42.         if (*L < *R)
  43.         {
  44.             *target = *L;
  45.             L++, nL--;
  46.         } else
  47.         {
  48.             *target = *R;
  49.             R++, nR--;
  50.         }
  51.     }
  52.     memcpy(target, nL ? L : R, (nL ? nL : nR) * sizeof(elem_t));
  53. }
  54.  
  55. void merge_sort(uint n, elem_t* a)
  56. {
  57.     if (n <= 1) return;
  58.     elem_t* tmp = cast(elem_t*, checked_malloc(n * sizeof(elem_t), "merge_sort buffer"));
  59.     _msort(n, a, tmp, true);
  60.     free(tmp);
  61. }
  62.  
  63. void print_array(const char *desc, uint n, elem_t* arr)
  64. {
  65.     printf("%s", desc);
  66.     for (uint i = 0; i < n; i++)
  67.         printf("%i ", arr[i]);
  68.     printf("\n");
  69. }
  70.  
  71. int main(int argc, char* argv[])
  72. {
  73.     elem_t arr[] = {5, 6, 1, 3, 9, 8, 112, 4, 66, -5};
  74.     print_array("Source array: ", array_size(arr), arr);
  75.  
  76.     printf("Sorting... ");
  77.     merge_sort(array_size(arr), arr);
  78.     printf("Done\n");
  79.  
  80.     print_array("Sorted array: ", array_size(arr), arr);
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement