quicksort.i.c 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. /* The routine quicksort was extracted from the GNU C Library qsort.c
  2. written by Douglas C. Schmidt (schmidt@ics.uci.edu)
  3. and adapted to guile by adding an extra pointer less
  4. to quicksort by Roland Orre <orre@nada.kth.se>.
  5. The reason to do this instead of using the library function qsort
  6. was to avoid dependency of the ANSI-C extensions for local functions
  7. and also to avoid obscure pool based solutions.
  8. This sorting routine is not much more efficient than the stable
  9. version but doesn't consume extra memory.
  10. */
  11. #define SWAP(a, b) do { const SCM _tmp = a; a = b; b = _tmp; } while (0)
  12. /* Order using quicksort. This implementation incorporates four
  13. optimizations discussed in Sedgewick:
  14. 1. Non-recursive, using an explicit stack of pointer that store the next
  15. array partition to sort. To save time, this maximum amount of space
  16. required to store an array of MAX_SIZE_T is allocated on the stack.
  17. Assuming a bit width of 32 bits for size_t, this needs only
  18. 32 * sizeof (stack_node) == 128 bytes. Pretty cheap, actually.
  19. 2. Chose the pivot element using a median-of-three decision tree. This
  20. reduces the probability of selecting a bad pivot value and eliminates
  21. certain extraneous comparisons.
  22. 3. Only quicksorts NR_ELEMS / MAX_THRESH partitions, leaving insertion sort
  23. to order the MAX_THRESH items within each partition. This is a big win,
  24. since insertion sort is faster for small, mostly sorted array segments.
  25. 4. The larger of the two sub-partitions is always pushed onto the
  26. stack first, with the algorithm then concentrating on the
  27. smaller partition. This *guarantees* no more than log (n)
  28. stack size is needed (actually O(1) in this case)! */
  29. /* Discontinue quicksort algorithm when partition gets below this size.
  30. * This particular magic number was chosen to work best on a Sun 4/260. */
  31. #define MAX_THRESH 4
  32. /* Inline stack abstraction: The stack size for quicksorting at most as many
  33. * elements as can be given by a value of type size_t is, as described above,
  34. * log (MAX_SIZE_T), which is the number of bits of size_t. More accurately,
  35. * we would only need ceil (log (MAX_SIZE_T / MAX_THRESH)), but this is
  36. * ignored below. */
  37. #define STACK_SIZE (8 * sizeof (size_t)) /* assume 8 bit char */
  38. #define PUSH(low, high) ((void) ((top->lo = (low)), (top->hi = (high)), ++top))
  39. #define POP(low, high) ((void) (--top, (low = top->lo), (high = top->hi)))
  40. #define STACK_NOT_EMPTY (stack < top)
  41. static void
  42. NAME (SCM *const base_ptr, size_t nr_elems, INC_PARAM
  43. scm_t_trampoline_2 cmp, SCM less)
  44. {
  45. /* Stack node declarations used to store unfulfilled partition obligations. */
  46. typedef struct {
  47. size_t lo;
  48. size_t hi;
  49. } stack_node;
  50. static const char s_buggy_less[] = "buggy less predicate used when sorting";
  51. #define ELT(i) base_ptr[(i)*INC]
  52. if (nr_elems == 0)
  53. /* Avoid lossage with unsigned arithmetic below. */
  54. return;
  55. if (nr_elems > MAX_THRESH)
  56. {
  57. size_t lo = 0;
  58. size_t hi = nr_elems-1;
  59. stack_node stack[STACK_SIZE];
  60. stack_node *top = stack + 1;
  61. while (STACK_NOT_EMPTY)
  62. {
  63. size_t left;
  64. size_t right;
  65. size_t mid = lo + (hi - lo) / 2;
  66. SCM pivot;
  67. /* Select median value from among LO, MID, and HI. Rearrange
  68. LO and HI so the three values are sorted. This lowers the
  69. probability of picking a pathological pivot value and
  70. skips a comparison for both the left and right. */
  71. SCM_TICK;
  72. if (scm_is_true ((*cmp) (less, ELT(mid), ELT(lo))))
  73. SWAP (ELT(mid), ELT(lo));
  74. if (scm_is_true ((*cmp) (less, ELT(hi), ELT(mid))))
  75. SWAP (ELT(mid), ELT(hi));
  76. else
  77. goto jump_over;
  78. if (scm_is_true ((*cmp) (less, ELT(mid), ELT(lo))))
  79. SWAP (ELT(mid), ELT(lo));
  80. jump_over:;
  81. pivot = ELT(mid);
  82. left = lo + 1;
  83. right = hi - 1;
  84. /* Here's the famous ``collapse the walls'' section of quicksort.
  85. Gotta like those tight inner loops! They are the main reason
  86. that this algorithm runs much faster than others. */
  87. do
  88. {
  89. while (scm_is_true ((*cmp) (less, ELT(left), pivot)))
  90. {
  91. left += 1;
  92. /* The comparison predicate may be buggy */
  93. if (left > hi)
  94. scm_misc_error (NULL, s_buggy_less, SCM_EOL);
  95. }
  96. while (scm_is_true ((*cmp) (less, pivot, ELT(right))))
  97. {
  98. right -= 1;
  99. /* The comparison predicate may be buggy */
  100. if (right < lo)
  101. scm_misc_error (NULL, s_buggy_less, SCM_EOL);
  102. }
  103. if (left < right)
  104. {
  105. SWAP (ELT(left), ELT(right));
  106. left += 1;
  107. right -= 1;
  108. }
  109. else if (left == right)
  110. {
  111. left += 1;
  112. right -= 1;
  113. break;
  114. }
  115. }
  116. while (left <= right);
  117. /* Set up pointers for next iteration. First determine whether
  118. left and right partitions are below the threshold size. If so,
  119. ignore one or both. Otherwise, push the larger partition's
  120. bounds on the stack and continue sorting the smaller one. */
  121. if ((size_t) (right - lo) <= MAX_THRESH)
  122. {
  123. if ((size_t) (hi - left) <= MAX_THRESH)
  124. /* Ignore both small partitions. */
  125. POP (lo, hi);
  126. else
  127. /* Ignore small left partition. */
  128. lo = left;
  129. }
  130. else if ((size_t) (hi - left) <= MAX_THRESH)
  131. /* Ignore small right partition. */
  132. hi = right;
  133. else if ((right - lo) > (hi - left))
  134. {
  135. /* Push larger left partition indices. */
  136. PUSH (lo, right);
  137. lo = left;
  138. }
  139. else
  140. {
  141. /* Push larger right partition indices. */
  142. PUSH (left, hi);
  143. hi = right;
  144. }
  145. }
  146. }
  147. /* Once the BASE_PTR array is partially sorted by quicksort the rest is
  148. completely sorted using insertion sort, since this is efficient for
  149. partitions below MAX_THRESH size. BASE_PTR points to the beginning of the
  150. array to sort, and END idexes the very last element in the array (*not*
  151. one beyond it!). */
  152. {
  153. size_t tmp = 0;
  154. size_t end = nr_elems-1;
  155. size_t thresh = min (end, MAX_THRESH);
  156. size_t run;
  157. /* Find smallest element in first threshold and place it at the
  158. array's beginning. This is the smallest array element,
  159. and the operation speeds up insertion sort's inner loop. */
  160. for (run = tmp + 1; run <= thresh; run += 1)
  161. if (scm_is_true ((*cmp) (less, ELT(run), ELT(tmp))))
  162. tmp = run;
  163. if (tmp != 0)
  164. SWAP (ELT(tmp), ELT(0));
  165. /* Insertion sort, running from left-hand-side up to right-hand-side. */
  166. run = 1;
  167. while (++run <= end)
  168. {
  169. SCM_TICK;
  170. tmp = run - 1;
  171. while (scm_is_true ((*cmp) (less, ELT(run), ELT(tmp))))
  172. {
  173. /* The comparison predicate may be buggy */
  174. if (tmp == 0)
  175. scm_misc_error (NULL, s_buggy_less, SCM_EOL);
  176. tmp -= 1;
  177. }
  178. tmp += 1;
  179. if (tmp != run)
  180. {
  181. SCM to_insert = ELT(run);
  182. size_t hi, lo;
  183. for (hi = lo = run; --lo >= tmp; hi = lo)
  184. ELT(hi) = ELT(lo);
  185. ELT(hi) = to_insert;
  186. }
  187. }
  188. }
  189. }
  190. #undef SWAP
  191. #undef MAX_THRESH
  192. #undef STACK_SIZE
  193. #undef PUSH
  194. #undef POP
  195. #undef STACK_NOT_EMPTY
  196. #undef ELT
  197. #undef NAME
  198. #undef INC_PARAM
  199. #undef INC