ctf-qsort_r.c 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. /* Copyright (C) 1991-2022 Free Software Foundation, Inc.
  2. This file is part of libctf (imported from Gnulib).
  3. Written by Douglas C. Schmidt (schmidt@ics.uci.edu).
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <https://www.gnu.org/licenses/>. */
  15. /* If you consider tuning this algorithm, you should consult first:
  16. Engineering a sort function; Jon Bentley and M. Douglas McIlroy;
  17. Software - Practice and Experience; Vol. 23 (11), 1249-1265, 1993. */
  18. #ifndef _LIBC
  19. # include <config.h>
  20. #endif
  21. #include <limits.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include "ctf-decls.h"
  25. #ifndef _LIBC
  26. # define _quicksort ctf_qsort_r
  27. # define __compar_d_fn_t compar_d_fn_t
  28. typedef int (*compar_d_fn_t) (const void *, const void *, void *);
  29. #endif
  30. /* Byte-wise swap two items of size SIZE. */
  31. #define SWAP(a, b, size) \
  32. do \
  33. { \
  34. size_t __size = (size); \
  35. char *__a = (a), *__b = (b); \
  36. do \
  37. { \
  38. char __tmp = *__a; \
  39. *__a++ = *__b; \
  40. *__b++ = __tmp; \
  41. } while (--__size > 0); \
  42. } while (0)
  43. /* Discontinue quicksort algorithm when partition gets below this size.
  44. This particular magic number was chosen to work best on a Sun 4/260. */
  45. #define MAX_THRESH 4
  46. /* Stack node declarations used to store unfulfilled partition obligations. */
  47. typedef struct
  48. {
  49. char *lo;
  50. char *hi;
  51. } stack_node;
  52. /* The next 4 #defines implement a very fast in-line stack abstraction. */
  53. /* The stack needs log (total_elements) entries (we could even subtract
  54. log(MAX_THRESH)). Since total_elements has type size_t, we get as
  55. upper bound for log (total_elements):
  56. bits per byte (CHAR_BIT) * sizeof(size_t). */
  57. #define STACK_SIZE (CHAR_BIT * sizeof(size_t))
  58. #define PUSH(low, high) ((void) ((top->lo = (low)), (top->hi = (high)), ++top))
  59. #define POP(low, high) ((void) (--top, (low = top->lo), (high = top->hi)))
  60. #define STACK_NOT_EMPTY (stack < top)
  61. /* Order size using quicksort. This implementation incorporates
  62. four optimizations discussed in Sedgewick:
  63. 1. Non-recursive, using an explicit stack of pointer that store the
  64. next array partition to sort. To save time, this maximum amount
  65. of space required to store an array of SIZE_MAX is allocated on the
  66. stack. Assuming a 32-bit (64 bit) integer for size_t, this needs
  67. only 32 * sizeof(stack_node) == 256 bytes (for 64 bit: 1024 bytes).
  68. Pretty cheap, actually.
  69. 2. Chose the pivot element using a median-of-three decision tree.
  70. This reduces the probability of selecting a bad pivot value and
  71. eliminates certain extraneous comparisons.
  72. 3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
  73. insertion sort to order the MAX_THRESH items within each partition.
  74. This is a big win, since insertion sort is faster for small, mostly
  75. sorted array segments.
  76. 4. The larger of the two sub-partitions is always pushed onto the
  77. stack first, with the algorithm then concentrating on the
  78. smaller partition. This *guarantees* no more than log (total_elems)
  79. stack size is needed (actually O(1) in this case)! */
  80. void
  81. _quicksort (void *const pbase, size_t total_elems, size_t size,
  82. __compar_d_fn_t cmp, void *arg)
  83. {
  84. char *base_ptr = (char *) pbase;
  85. const size_t max_thresh = MAX_THRESH * size;
  86. if (total_elems == 0)
  87. /* Avoid lossage with unsigned arithmetic below. */
  88. return;
  89. if (total_elems > MAX_THRESH)
  90. {
  91. char *lo = base_ptr;
  92. char *hi = &lo[size * (total_elems - 1)];
  93. stack_node stack[STACK_SIZE];
  94. stack_node *top = stack;
  95. PUSH (NULL, NULL);
  96. while (STACK_NOT_EMPTY)
  97. {
  98. char *left_ptr;
  99. char *right_ptr;
  100. /* Select median value from among LO, MID, and HI. Rearrange
  101. LO and HI so the three values are sorted. This lowers the
  102. probability of picking a pathological pivot value and
  103. skips a comparison for both the LEFT_PTR and RIGHT_PTR in
  104. the while loops. */
  105. char *mid = lo + size * ((hi - lo) / size >> 1);
  106. if ((*cmp) ((void *) mid, (void *) lo, arg) < 0)
  107. SWAP (mid, lo, size);
  108. if ((*cmp) ((void *) hi, (void *) mid, arg) < 0)
  109. SWAP (mid, hi, size);
  110. else
  111. goto jump_over;
  112. if ((*cmp) ((void *) mid, (void *) lo, arg) < 0)
  113. SWAP (mid, lo, size);
  114. jump_over:;
  115. left_ptr = lo + size;
  116. right_ptr = hi - size;
  117. /* Here's the famous ``collapse the walls'' section of quicksort.
  118. Gotta like those tight inner loops! They are the main reason
  119. that this algorithm runs much faster than others. */
  120. do
  121. {
  122. while ((*cmp) ((void *) left_ptr, (void *) mid, arg) < 0)
  123. left_ptr += size;
  124. while ((*cmp) ((void *) mid, (void *) right_ptr, arg) < 0)
  125. right_ptr -= size;
  126. if (left_ptr < right_ptr)
  127. {
  128. SWAP (left_ptr, right_ptr, size);
  129. if (mid == left_ptr)
  130. mid = right_ptr;
  131. else if (mid == right_ptr)
  132. mid = left_ptr;
  133. left_ptr += size;
  134. right_ptr -= size;
  135. }
  136. else if (left_ptr == right_ptr)
  137. {
  138. left_ptr += size;
  139. right_ptr -= size;
  140. break;
  141. }
  142. }
  143. while (left_ptr <= right_ptr);
  144. /* Set up pointers for next iteration. First determine whether
  145. left and right partitions are below the threshold size. If so,
  146. ignore one or both. Otherwise, push the larger partition's
  147. bounds on the stack and continue sorting the smaller one. */
  148. if ((size_t) (right_ptr - lo) <= max_thresh)
  149. {
  150. if ((size_t) (hi - left_ptr) <= max_thresh)
  151. /* Ignore both small partitions. */
  152. POP (lo, hi);
  153. else
  154. /* Ignore small left partition. */
  155. lo = left_ptr;
  156. }
  157. else if ((size_t) (hi - left_ptr) <= max_thresh)
  158. /* Ignore small right partition. */
  159. hi = right_ptr;
  160. else if ((right_ptr - lo) > (hi - left_ptr))
  161. {
  162. /* Push larger left partition indices. */
  163. PUSH (lo, right_ptr);
  164. lo = left_ptr;
  165. }
  166. else
  167. {
  168. /* Push larger right partition indices. */
  169. PUSH (left_ptr, hi);
  170. hi = right_ptr;
  171. }
  172. }
  173. }
  174. /* Once the BASE_PTR array is partially sorted by quicksort the rest
  175. is completely sorted using insertion sort, since this is efficient
  176. for partitions below MAX_THRESH size. BASE_PTR points to the beginning
  177. of the array to sort, and END_PTR points at the very last element in
  178. the array (*not* one beyond it!). */
  179. #define min(x, y) ((x) < (y) ? (x) : (y))
  180. {
  181. char *const end_ptr = &base_ptr[size * (total_elems - 1)];
  182. char *tmp_ptr = base_ptr;
  183. char *thresh = min(end_ptr, base_ptr + max_thresh);
  184. char *run_ptr;
  185. /* Find smallest element in first threshold and place it at the
  186. array's beginning. This is the smallest array element,
  187. and the operation speeds up insertion sort's inner loop. */
  188. for (run_ptr = tmp_ptr + size; run_ptr <= thresh; run_ptr += size)
  189. if ((*cmp) ((void *) run_ptr, (void *) tmp_ptr, arg) < 0)
  190. tmp_ptr = run_ptr;
  191. if (tmp_ptr != base_ptr)
  192. SWAP (tmp_ptr, base_ptr, size);
  193. /* Insertion sort, running from left-hand-side up to right-hand-side. */
  194. run_ptr = base_ptr + size;
  195. while ((run_ptr += size) <= end_ptr)
  196. {
  197. tmp_ptr = run_ptr - size;
  198. while ((*cmp) ((void *) run_ptr, (void *) tmp_ptr, arg) < 0)
  199. tmp_ptr -= size;
  200. tmp_ptr += size;
  201. if (tmp_ptr != run_ptr)
  202. {
  203. char *trav;
  204. trav = run_ptr + size;
  205. while (--trav >= run_ptr)
  206. {
  207. char c = *trav;
  208. char *hi, *lo;
  209. for (hi = lo = trav; (lo -= size) >= tmp_ptr; hi = lo)
  210. *hi = *lo;
  211. *hi = c;
  212. }
  213. }
  214. }
  215. }
  216. }