Guest User

Untitled

a guest
Dec 12th, 2018
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.28 KB | None | 0 0
  1. #define stb_declare_sort(FUNCNAME, TYPE) \
  2. void FUNCNAME(TYPE *p, int n)
  3. #define stb_define_sort(FUNCNAME,TYPE,COMPARE) \
  4. stb__define_sort( void, FUNCNAME,TYPE,COMPARE)
  5. #define stb_define_sort_static(FUNCNAME,TYPE,COMPARE) \
  6. stb__define_sort(static void, FUNCNAME,TYPE,COMPARE)
  7.  
  8. #define stb__define_sort(MODE, FUNCNAME, TYPE, COMPARE) \
  9. \
  10. static void STB_(FUNCNAME,_ins_sort)(TYPE *p, int n) \
  11. { \
  12. int i,j; \
  13. for (i=1; i < n; ++i) { \
  14. TYPE t = p[i], *a = &t; \
  15. j = i; \
  16. while (j > 0) { \
  17. TYPE *b = &p[j-1]; \
  18. int c = COMPARE; \
  19. if (!c) break; \
  20. p[j] = p[j-1]; \
  21. --j; \
  22. } \
  23. if (i != j) \
  24. p[j] = t; \
  25. } \
  26. } \
  27. \
  28. static void STB_(FUNCNAME,_quicksort)(TYPE *p, int n) \
  29. { \
  30. /* threshhold for transitioning to insertion sort */ \
  31. while (n > 12) { \
  32. TYPE *a,*b,t; \
  33. int c01,c12,c,m,i,j; \
  34. \
  35. /* compute median of three */ \
  36. m = n >> 1; \
  37. a = &p[0]; \
  38. b = &p[m]; \
  39. c = COMPARE; \
  40. c01 = c; \
  41. a = &p[m]; \
  42. b = &p[n-1]; \
  43. c = COMPARE; \
  44. c12 = c; \
  45. /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ \
  46. if (c01 != c12) { \
  47. /* otherwise, we'll need to swap something else to middle */ \
  48. int z; \
  49. a = &p[0]; \
  50. b = &p[n-1]; \
  51. c = COMPARE; \
  52. /* 0>mid && mid<n: 0>n => n; 0<n => 0 */ \
  53. /* 0<mid && mid>n: 0>n => 0; 0<n => n */ \
  54. z = (c == c12) ? 0 : n-1; \
  55. t = p[z]; \
  56. p[z] = p[m]; \
  57. p[m] = t; \
  58. } \
  59. /* now p[m] is the median-of-three */ \
  60. /* swap it to the beginning so it won't move around */ \
  61. t = p[0]; \
  62. p[0] = p[m]; \
  63. p[m] = t; \
  64. \
  65. /* partition loop */ \
  66. i=1; \
  67. j=n-1; \
  68. for(;;) { \
  69. /* handling of equality is crucial here */ \
  70. /* for sentinels & efficiency with duplicates */ \
  71. b = &p[0]; \
  72. for (;;++i) { \
  73. a=&p[i]; \
  74. c = COMPARE; \
  75. if (!c) break; \
  76. } \
  77. a = &p[0]; \
  78. for (;;--j) { \
  79. b=&p[j]; \
  80. c = COMPARE; \
  81. if (!c) break; \
  82. } \
  83. /* make sure we haven't crossed */ \
  84. if (i >= j) break; \
  85. t = p[i]; \
  86. p[i] = p[j]; \
  87. p[j] = t; \
  88. \
  89. ++i; \
  90. --j; \
  91. } \
  92. /* recurse on smaller side, iterate on larger */ \
  93. if (j < (n-i)) { \
  94. STB_(FUNCNAME,_quicksort)(p,j); \
  95. p = p+i; \
  96. n = n-i; \
  97. } else { \
  98. STB_(FUNCNAME,_quicksort)(p+i, n-i); \
  99. n = j; \
  100. } \
  101. } \
  102. } \
  103. \
  104. MODE FUNCNAME(TYPE *p, int n) \
  105. { \
  106. STB_(FUNCNAME, _quicksort)(p, n); \
  107. STB_(FUNCNAME, _ins_sort)(p, n); \
  108. }
Add Comment
Please, Sign In to add comment