fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <math.h>
  5.  
  6. #define EPS 1E-6
  7.  
  8. int compare_newdouble(const void *left, const void *right);
  9. void mergesort(void *base, size_t n, size_t size, int (*compar)(const void *, const void *));
  10.  
  11.  
  12.  
  13. int compare_newdouble(const void *left, const void *right)
  14. {
  15. double *p = (double*)left;
  16. double *q = (double*)right;
  17.  
  18. if(fabs(fabs(*p) - fabs(*q)) < EPS)
  19. {
  20. return 0;
  21. }
  22.  
  23. if(fabs(*p) > fabs(*q))
  24. {
  25. return 1;
  26. }
  27.  
  28. return -1;
  29. }
  30.  
  31. void mergesort(void *base, size_t n, size_t size, int (*compar)(const void *, const void *))
  32. {
  33. const size_t mid = n/2;
  34. size_t l = 0, r = 0, a = 0;
  35. size_t i;
  36. void *add=malloc(size*n);
  37.  
  38. if(n < 2)
  39. {
  40. return;
  41. }
  42.  
  43. mergesort(base, mid, size, compar); //left array
  44. mergesort(base+size*mid, n-mid, size, compar); //right array
  45.  
  46. while(l < mid && r < (n-mid))
  47. {
  48. if((*compar)(base+size*l, base+size*mid+size*r) == -1)
  49. {
  50. memcpy((add+size*a), (base+size*l), size); // putting the memory from left to add
  51. a++;
  52. l++;
  53. }
  54. else
  55. {
  56. memcpy((add+size*a), (base+size*mid+size*r), size); // putting the memory from right to add
  57. a++;
  58. r++;
  59. }
  60. }
  61.  
  62. // Здесь были циклы
  63.  
  64. if(l < mid)
  65. {
  66. memcpy((add+size*a), (base+size*l), size * (mid - l));
  67. }
  68. else if(r < (n-mid))
  69. {
  70. memcpy((add+size*a), (base+size*mid+size*r), size * (n-mid - r));
  71.  
  72. }
  73.  
  74. memcpy(base, add, size*n);
  75.  
  76. free(add);
  77. }
  78.  
  79. int main(void)
  80. {
  81. int n = 15, i;
  82. double *a;
  83.  
  84. a=malloc(sizeof(double)*n);
  85.  
  86. for(i = 0; i < n; i++)
  87. {
  88. a[i] = n - i;
  89. }
  90.  
  91. mergesort(a, n, sizeof(double), &compare_newdouble);
  92.  
  93. for(i = 0; i < n; i++)
  94. {
  95. printf("%lf ", a[i]);
  96. }
  97.  
  98. free(a);
  99.  
  100. return 0;
  101. }
  102.  
Success #stdin #stdout 0s 2244KB
stdin
Standard input is empty
stdout
1.000000 2.000000 3.000000 4.000000 5.000000 6.000000 7.000000 8.000000 9.000000 10.000000 11.000000 12.000000 13.000000 14.000000 15.000000