qsort.c 8.2 KB

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