当前位置:   article > 正文

归并排序(非递归)(C语言)_c归并排序非递归csdn

c归并排序非递归csdn

判题网站:PTA

得分:25/25

  1. #include "stdio.h"
  2. #include "stdlib.h"
  3. #pragma warning(disable:4996)
  4. void Swap(long A[], long i, long j);
  5. void Merge(long A[], long temp[], int L, int R, int RightEnd);
  6. void MSort(long A[], long temp[], int L, int R);
  7. void MergeSort(long A[], int N);
  8. void MSort2(long A[], int L, int R);
  9. int main()
  10. {
  11. int N;
  12. scanf("%d", &N);
  13. long number[N];
  14. for (int i = 0; i < N; i++)
  15. {
  16. scanf("%ld", &number[i]);
  17. }
  18. MergeSort(number, N);
  19. for (int i = 0; i < N - 1; i++)
  20. {
  21. printf("%ld ", number[i]);
  22. }
  23. printf("%ld", number[N - 1]);
  24. return 0;
  25. }
  26. void Swap(long A[], long i, long j)
  27. {
  28. long temp;
  29. temp = A[i];
  30. A[i] = A[j];
  31. A[j] = temp;
  32. }
  33. void Merge(long A[], long temp[], int L, int R, int RightEnd)
  34. {
  35. int LeftEnd;
  36. LeftEnd = R - 1;
  37. int j = L;
  38. int i = 0;
  39. int NumElement = RightEnd - L + 1;
  40. while (L <= LeftEnd && R <= RightEnd)
  41. {
  42. if (A[L] > A[R])
  43. {
  44. temp[j] = A[R];
  45. j++;
  46. R++;
  47. }
  48. else
  49. {
  50. temp[j] = A[L];
  51. j++;
  52. L++;
  53. }
  54. }
  55. while (L <= LeftEnd)
  56. {
  57. temp[j] = A[L];
  58. j++;
  59. L++;
  60. }
  61. while (R <= RightEnd)
  62. {
  63. temp[j] = A[R];
  64. j++;
  65. R++;
  66. }
  67. for (i = 0; i < NumElement; i++, RightEnd--)
  68. {
  69. A[RightEnd] = temp[RightEnd];
  70. }
  71. }
  72. void MSort(long A[], long temp[], int L, int R)
  73. {
  74. int center;
  75. center = (L + R) / 2;
  76. if (L < R)
  77. {
  78. MSort(A, temp, L, center);
  79. MSort(A, temp, center + 1, R);
  80. Merge(A, temp, L, center + 1, R);
  81. }
  82. }
  83. void MergeSort(long A[], int N)
  84. {
  85. MSort2(A, 0, N);
  86. }
  87. void MSort2(long A[], int L, int R)
  88. {
  89. long temp[R];
  90. int length = 1;
  91. int i = 0;
  92. if (R == 1)
  93. {
  94. return;
  95. }
  96. for (length;length<R; length *= 2)
  97. {
  98. for (i = 0; i <= R - 2 * length; i += length * 2)
  99. Merge(A, temp, i, length + i, i + length*2-1);
  100. if (i + length < R)
  101. {
  102. Merge(A, temp, i, i + length, R - 1);
  103. }
  104. }
  105. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/342792
推荐阅读
相关标签
  

闽ICP备14008679号