fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. void merge(int L[], int left_count, int R[], int right_count, int a[]){
  6. int i = 0, j = 0, k = 0;
  7.  
  8. while(i < left_count && j < right_count){
  9. if(L[i] <= R[j])
  10. a[k] = L[i++];
  11. else
  12. a[k] = R[j++];
  13. k++;
  14. }
  15. if(i == left_count)
  16. memcpy(&a[k], &R[j], sizeof(R[0]) * (right_count - j));
  17. else
  18. memcpy(&a[k], &L[j], sizeof(L[0]) * (left_count - i));
  19. free(L);
  20. free(R);
  21. }
  22.  
  23. void mergesort(int a[], int n){
  24. int i;
  25. int split = n / 2;
  26. int *L = (int *)malloc(split * sizeof(a[0]));
  27. int *R = (int *)malloc((n - split) * sizeof(a[0]));
  28.  
  29. if(n > 1){
  30. for(i = 0; i < split; i++)
  31. L[i] = a[i];
  32. for(i = split; i < n; i++)
  33. R[i - split] = a[i];
  34. mergesort(L, split);
  35. mergesort(R, n - split);
  36. merge(L, split, R, n - split, a);
  37. }
  38. }
  39.  
  40. int main(int argc, char *argv[]){
  41. int i;
  42. int v[10] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10};
  43.  
  44. mergesort(v, 10);
  45.  
  46. for(i = 0; i < 10; i++)
  47. printf("%d ", v[i]);
  48.  
  49. scanf("%d", &i);
  50. return 0;
  51. }
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
1 2 3 4 5 6 7 8 9 10