quicksort.i.c 6.9 KB

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