sort.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. /* Copyright (C) 1999, 2000, 2002 Free Software Foundation, Inc.
  2. * This program is free software; you can redistribute it and/or modify
  3. * it under the terms of the GNU General Public License as published by
  4. * the Free Software Foundation; either version 2, or (at your option)
  5. * any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this software; see the file COPYING. If not, write to
  14. * the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  15. * Boston, MA 02111-1307 USA
  16. *
  17. * As a special exception, the Free Software Foundation gives permission
  18. * for additional uses of the text contained in its release of GUILE.
  19. *
  20. * The exception is that, if you link the GUILE library with other files
  21. * to produce an executable, this does not by itself cause the
  22. * resulting executable to be covered by the GNU General Public License.
  23. * Your use of that executable is in no way restricted on account of
  24. * linking the GUILE library code into it.
  25. *
  26. * This exception does not however invalidate any other reasons why
  27. * the executable file might be covered by the GNU General Public License.
  28. *
  29. * This exception applies only to the code released by the
  30. * Free Software Foundation under the name GUILE. If you copy
  31. * code from other Free Software Foundation releases into a copy of
  32. * GUILE, as the General Public License permits, the exception does
  33. * not apply to the code that you add in this way. To avoid misleading
  34. * anyone as to the status of such modified files, you must delete
  35. * this exception notice from them.
  36. *
  37. * If you write modifications of your own for GUILE, it is your choice
  38. * whether to permit this exception to apply to your modifications.
  39. * If you do not wish that, delete this exception notice. */
  40. /* Written in December 1998 by Roland Orre <orre@nada.kth.se>
  41. * This implements the same sort interface as slib/sort.scm
  42. * for lists and vectors where slib defines:
  43. * sorted?, merge, merge!, sort, sort!
  44. * For scsh compatibility sort-list and sort-list! are also defined.
  45. * In cases where a stable-sort is required use stable-sort or
  46. * stable-sort!. An additional feature is
  47. * (restricted-vector-sort! vector less? startpos endpos)
  48. * which allows you to sort part of a vector.
  49. * Thanks to Aubrey Jaffer for the slib/sort.scm library.
  50. * Thanks to Richard A. O'Keefe (based on Prolog code by D.H.D.Warren)
  51. * for the merge sort inspiration.
  52. * Thanks to Douglas C. Schmidt (schmidt@ics.uci.edu) for the
  53. * quicksort code.
  54. */
  55. /* We need this to get the definitions for HAVE_ALLOCA_H, etc. */
  56. #include "libguile/scmconfig.h"
  57. /* AIX requires this to be the first thing in the file. The #pragma
  58. directive is indented so pre-ANSI compilers will ignore it, rather
  59. than choke on it. */
  60. #ifndef __GNUC__
  61. # if HAVE_ALLOCA_H
  62. # include <alloca.h>
  63. # else
  64. # ifdef _AIX
  65. #pragma alloca
  66. # else
  67. # ifndef alloca /* predefined by HP cc +Olibcalls */
  68. char *alloca ();
  69. # endif
  70. # endif
  71. # endif
  72. #endif
  73. #include "libguile/_scm.h"
  74. #include "libguile/eval.h"
  75. #include "libguile/unif.h"
  76. #include "libguile/ramap.h"
  77. #include "libguile/alist.h"
  78. #include "libguile/feature.h"
  79. #include "libguile/vectors.h"
  80. #include "libguile/validate.h"
  81. #include "libguile/sort.h"
  82. /* The routine quicksort was extracted from the GNU C Library qsort.c
  83. written by Douglas C. Schmidt (schmidt@ics.uci.edu)
  84. and adapted to guile by adding an extra pointer less
  85. to quicksort by Roland Orre <orre@nada.kth.se>.
  86. The reason to do this instead of using the library function qsort
  87. was to avoid dependency of the ANSI-C extensions for local functions
  88. and also to avoid obscure pool based solutions.
  89. This sorting routine is not much more efficient than the stable
  90. version but doesn't consume extra memory.
  91. */
  92. /* Byte-wise swap two items of size SIZE. */
  93. #define SWAP(a, b, size) \
  94. do \
  95. { \
  96. register size_t __size = (size); \
  97. register char *__a = (a), *__b = (b); \
  98. do \
  99. { \
  100. char __tmp = *__a; \
  101. *__a++ = *__b; \
  102. *__b++ = __tmp; \
  103. } while (--__size > 0); \
  104. } while (0)
  105. /* Discontinue quicksort algorithm when partition gets below this size.
  106. This particular magic number was chosen to work best on a Sun 4/260. */
  107. #define MAX_THRESH 4
  108. /* Stack node declarations used to store unfulfilled partition obligations. */
  109. typedef struct
  110. {
  111. char *lo;
  112. char *hi;
  113. }
  114. stack_node;
  115. /* The next 4 #defines implement a very fast in-line stack abstraction. */
  116. #define STACK_SIZE (8 * sizeof(unsigned long int))
  117. #define PUSH(low, high) ((void) ((top->lo = (low)), (top->hi = (high)), ++top))
  118. #define POP(low, high) ((void) (--top, (low = top->lo), (high = top->hi)))
  119. #define STACK_NOT_EMPTY (stack < top)
  120. /* Order size using quicksort. This implementation incorporates
  121. four optimizations discussed in Sedgewick:
  122. 1. Non-recursive, using an explicit stack of pointer that store the
  123. next array partition to sort. To save time, this maximum amount
  124. of space required to store an array of MAX_INT is allocated on the
  125. stack. Assuming a 32-bit integer, this needs only 32 *
  126. sizeof(stack_node) == 136 bits. Pretty cheap, actually.
  127. 2. Chose the pivot element using a median-of-three decision tree.
  128. This reduces the probability of selecting a bad pivot value and
  129. eliminates certain extraneous comparisons.
  130. 3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
  131. insertion sort to order the MAX_THRESH items within each partition.
  132. This is a big win, since insertion sort is faster for small, mostly
  133. sorted array segments.
  134. 4. The larger of the two sub-partitions is always pushed onto the
  135. stack first, with the algorithm then concentrating on the
  136. smaller partition. This *guarantees* no more than log (n)
  137. stack size is needed (actually O(1) in this case)! */
  138. typedef int (*cmp_fun_t) (SCM less,
  139. const void*,
  140. const void*);
  141. static const char s_buggy_less[] = "buggy less predicate used when sorting";
  142. static void
  143. quicksort (void *const pbase,
  144. size_t total_elems,
  145. size_t size,
  146. cmp_fun_t cmp,
  147. SCM less)
  148. {
  149. register char *base_ptr = (char *) pbase;
  150. /* Allocating SIZE bytes for a pivot buffer facilitates a better
  151. algorithm below since we can do comparisons directly on the pivot. */
  152. char *pivot_buffer = (char *) alloca (size);
  153. const size_t max_thresh = MAX_THRESH * size;
  154. if (total_elems == 0)
  155. /* Avoid lossage with unsigned arithmetic below. */
  156. return;
  157. if (total_elems > MAX_THRESH)
  158. {
  159. char *lo = base_ptr;
  160. char *hi = &lo[size * (total_elems - 1)];
  161. /* Largest size needed for 32-bit int!!! */
  162. stack_node stack[STACK_SIZE];
  163. stack_node *top = stack + 1;
  164. while (STACK_NOT_EMPTY)
  165. {
  166. char *left_ptr;
  167. char *right_ptr;
  168. char *pivot = pivot_buffer;
  169. /* Select median value from among LO, MID, and HI. Rearrange
  170. LO and HI so the three values are sorted. This lowers the
  171. probability of picking a pathological pivot value and
  172. skips a comparison for both the LEFT_PTR and RIGHT_PTR. */
  173. char *mid = lo + size * ((hi - lo) / size >> 1);
  174. if ((*cmp) (less, (void *) mid, (void *) lo))
  175. SWAP (mid, lo, size);
  176. if ((*cmp) (less, (void *) hi, (void *) mid))
  177. SWAP (mid, hi, size);
  178. else
  179. goto jump_over;
  180. if ((*cmp) (less, (void *) mid, (void *) lo))
  181. SWAP (mid, lo, size);
  182. jump_over:;
  183. memcpy (pivot, mid, size);
  184. pivot = pivot_buffer;
  185. left_ptr = lo + size;
  186. right_ptr = hi - size;
  187. /* Here's the famous ``collapse the walls'' section of quicksort.
  188. Gotta like those tight inner loops! They are the main reason
  189. that this algorithm runs much faster than others. */
  190. do
  191. {
  192. while ((*cmp) (less, (void *) left_ptr, (void *) pivot))
  193. {
  194. left_ptr += size;
  195. /* The comparison predicate may be buggy */
  196. if (left_ptr > hi)
  197. scm_misc_error (NULL, s_buggy_less, SCM_EOL);
  198. }
  199. while ((*cmp) (less, (void *) pivot, (void *) right_ptr))
  200. {
  201. right_ptr -= size;
  202. /* The comparison predicate may be buggy */
  203. if (right_ptr < lo)
  204. scm_misc_error (NULL, s_buggy_less, SCM_EOL);
  205. }
  206. if (left_ptr < right_ptr)
  207. {
  208. SWAP (left_ptr, right_ptr, size);
  209. left_ptr += size;
  210. right_ptr -= size;
  211. }
  212. else if (left_ptr == right_ptr)
  213. {
  214. left_ptr += size;
  215. right_ptr -= size;
  216. break;
  217. }
  218. }
  219. while (left_ptr <= right_ptr);
  220. /* Set up pointers for next iteration. First determine whether
  221. left and right partitions are below the threshold size. If so,
  222. ignore one or both. Otherwise, push the larger partition's
  223. bounds on the stack and continue sorting the smaller one. */
  224. if ((size_t) (right_ptr - lo) <= max_thresh)
  225. {
  226. if ((size_t) (hi - left_ptr) <= max_thresh)
  227. /* Ignore both small partitions. */
  228. POP (lo, hi);
  229. else
  230. /* Ignore small left partition. */
  231. lo = left_ptr;
  232. }
  233. else if ((size_t) (hi - left_ptr) <= max_thresh)
  234. /* Ignore small right partition. */
  235. hi = right_ptr;
  236. else if ((right_ptr - lo) > (hi - left_ptr))
  237. {
  238. /* Push larger left partition indices. */
  239. PUSH (lo, right_ptr);
  240. lo = left_ptr;
  241. }
  242. else
  243. {
  244. /* Push larger right partition indices. */
  245. PUSH (left_ptr, hi);
  246. hi = right_ptr;
  247. }
  248. }
  249. }
  250. /* Once the BASE_PTR array is partially sorted by quicksort the rest
  251. is completely sorted using insertion sort, since this is efficient
  252. for partitions below MAX_THRESH size. BASE_PTR points to the beginning
  253. of the array to sort, and END_PTR points at the very last element in
  254. the array (*not* one beyond it!). */
  255. {
  256. char *const end_ptr = &base_ptr[size * (total_elems - 1)];
  257. char *tmp_ptr = base_ptr;
  258. char *thresh = min (end_ptr, base_ptr + max_thresh);
  259. register char *run_ptr;
  260. /* Find smallest element in first threshold and place it at the
  261. array's beginning. This is the smallest array element,
  262. and the operation speeds up insertion sort's inner loop. */
  263. for (run_ptr = tmp_ptr + size; run_ptr <= thresh; run_ptr += size)
  264. if ((*cmp) (less, (void *) run_ptr, (void *) tmp_ptr))
  265. tmp_ptr = run_ptr;
  266. if (tmp_ptr != base_ptr)
  267. SWAP (tmp_ptr, base_ptr, size);
  268. /* Insertion sort, running from left-hand-side up to right-hand-side. */
  269. run_ptr = base_ptr + size;
  270. while ((run_ptr += size) <= end_ptr)
  271. {
  272. tmp_ptr = run_ptr - size;
  273. while ((*cmp) (less, (void *) run_ptr, (void *) tmp_ptr))
  274. {
  275. tmp_ptr -= size;
  276. /* The comparison predicate may be buggy */
  277. if (tmp_ptr < base_ptr)
  278. scm_misc_error (NULL, s_buggy_less, SCM_EOL);
  279. }
  280. tmp_ptr += size;
  281. if (tmp_ptr != run_ptr)
  282. {
  283. char *trav;
  284. trav = run_ptr + size;
  285. while (--trav >= run_ptr)
  286. {
  287. char c = *trav;
  288. char *hi, *lo;
  289. for (hi = lo = trav; (lo -= size) >= tmp_ptr; hi = lo)
  290. *hi = *lo;
  291. *hi = c;
  292. }
  293. }
  294. }
  295. }
  296. } /* quicksort */
  297. /* comparison routines */
  298. static int
  299. subr2less (SCM less, const void *a, const void *b)
  300. {
  301. return SCM_NFALSEP (SCM_SUBRF (less) (*(SCM *) a, *(SCM *) b));
  302. } /* subr2less */
  303. static int
  304. subr2oless (SCM less, const void *a, const void *b)
  305. {
  306. return SCM_NFALSEP (SCM_SUBRF (less) (*(SCM *) a,
  307. *(SCM *) b,
  308. SCM_UNDEFINED));
  309. } /* subr2oless */
  310. static int
  311. lsubrless (SCM less, const void *a, const void *b)
  312. {
  313. return SCM_NFALSEP (SCM_SUBRF (less)
  314. (scm_cons (*(SCM *) a,
  315. scm_cons (*(SCM *) b, SCM_EOL))));
  316. } /* lsubrless */
  317. static int
  318. closureless (SCM code, const void *a, const void *b)
  319. {
  320. SCM env = SCM_EXTEND_ENV (SCM_CAR (SCM_CODE (code)),
  321. scm_cons (*(SCM *) a,
  322. scm_cons (*(SCM *) b, SCM_EOL)),
  323. SCM_ENV (code));
  324. /* Evaluate the closure body */
  325. return SCM_NFALSEP (scm_eval_body (SCM_CDR (SCM_CODE (code)), env));
  326. } /* closureless */
  327. static int
  328. applyless (SCM less, const void *a, const void *b)
  329. {
  330. return SCM_NFALSEP (scm_apply (less,
  331. scm_cons (*(SCM *) a,
  332. scm_cons (*(SCM *) b, SCM_EOL)),
  333. SCM_EOL));
  334. } /* applyless */
  335. static cmp_fun_t
  336. scm_cmp_function (SCM p)
  337. {
  338. switch (SCM_TYP7 (p))
  339. {
  340. case scm_tc7_subr_2:
  341. case scm_tc7_rpsubr:
  342. case scm_tc7_asubr:
  343. return subr2less;
  344. case scm_tc7_subr_2o:
  345. return subr2oless;
  346. case scm_tc7_lsubr:
  347. return lsubrless;
  348. case scm_tcs_closures:
  349. return closureless;
  350. default:
  351. return applyless;
  352. }
  353. } /* scm_cmp_function */
  354. /* Question: Is there any need to make this a more general array sort?
  355. It is probably enough to manage the vector type. */
  356. /* endpos equal as for substring, i.e. endpos is not included. */
  357. /* More natural with length? */
  358. SCM_DEFINE (scm_restricted_vector_sort_x, "restricted-vector-sort!", 4, 0, 0,
  359. (SCM vec, SCM less, SCM startpos, SCM endpos),
  360. "")
  361. #define FUNC_NAME s_scm_restricted_vector_sort_x
  362. {
  363. size_t vlen, spos, len, size = sizeof (SCM);
  364. SCM *vp;
  365. SCM_VALIDATE_NIM (1,vec);
  366. SCM_VALIDATE_NIM (2,less);
  367. switch (SCM_TYP7 (vec))
  368. {
  369. case scm_tc7_vector: /* the only type we manage is vector */
  370. break;
  371. #if 0 /* HAVE_ARRAYS */
  372. case scm_tc7_ivect: /* long */
  373. case scm_tc7_uvect: /* unsigned */
  374. case scm_tc7_fvect: /* float */
  375. case scm_tc7_dvect: /* double */
  376. #endif
  377. default:
  378. SCM_WTA (1,vec);
  379. }
  380. vp = SCM_VELTS (vec); /* vector pointer */
  381. vlen = SCM_LENGTH (vec);
  382. SCM_VALIDATE_INUM_COPY (3,startpos,spos);
  383. SCM_ASSERT_RANGE (3,startpos,(spos >= 0) && (spos <= vlen));
  384. SCM_VALIDATE_INUM_RANGE (4,endpos,0,vlen+1);
  385. len = SCM_INUM (endpos) - spos;
  386. quicksort (&vp[spos], len, size, scm_cmp_function (less), less);
  387. return SCM_UNSPECIFIED;
  388. /* return vec; */
  389. }
  390. #undef FUNC_NAME
  391. /* (sorted? sequence less?)
  392. * is true when sequence is a list (x0 x1 ... xm) or a vector #(x0 ... xm)
  393. * such that for all 1 <= i <= m,
  394. * (not (less? (list-ref list i) (list-ref list (- i 1)))). */
  395. SCM_DEFINE (scm_sorted_p, "sorted?", 2, 0, 0,
  396. (SCM items, SCM less),
  397. "")
  398. #define FUNC_NAME s_scm_sorted_p
  399. {
  400. long len, j; /* list/vector length, temp j */
  401. SCM item, rest; /* rest of items loop variable */
  402. SCM *vp;
  403. cmp_fun_t cmp = scm_cmp_function (less);
  404. if (SCM_NULLP (items))
  405. return SCM_BOOL_T;
  406. SCM_VALIDATE_NIM (1,items);
  407. SCM_VALIDATE_NIM (2,less);
  408. if (SCM_CONSP (items))
  409. {
  410. len = scm_ilength (items); /* also checks that it's a pure list */
  411. SCM_ASSERT_RANGE (1,items,len >= 0);
  412. if (len <= 1)
  413. return SCM_BOOL_T;
  414. item = SCM_CAR (items);
  415. rest = SCM_CDR (items);
  416. j = len - 1;
  417. while (j > 0)
  418. {
  419. if ((*cmp) (less, SCM_CARLOC(rest), &item))
  420. return SCM_BOOL_F;
  421. else
  422. {
  423. item = SCM_CAR (rest);
  424. rest = SCM_CDR (rest);
  425. j--;
  426. }
  427. }
  428. return SCM_BOOL_T;
  429. }
  430. else
  431. {
  432. switch (SCM_TYP7 (items))
  433. {
  434. case scm_tc7_vector:
  435. {
  436. vp = SCM_VELTS (items); /* vector pointer */
  437. len = SCM_LENGTH (items);
  438. j = len - 1;
  439. while (j > 0)
  440. {
  441. if ((*cmp) (less, &vp[1], vp))
  442. return SCM_BOOL_F;
  443. else
  444. {
  445. vp++;
  446. j--;
  447. }
  448. }
  449. return SCM_BOOL_T;
  450. }
  451. break;
  452. #if 0 /* HAVE_ARRAYS */
  453. case scm_tc7_ivect: /* long */
  454. case scm_tc7_uvect: /* unsigned */
  455. case scm_tc7_fvect: /* float */
  456. case scm_tc7_dvect: /* double */
  457. #endif
  458. default:
  459. SCM_WTA (1,items);
  460. }
  461. }
  462. return SCM_BOOL_F;
  463. }
  464. #undef FUNC_NAME
  465. /* (merge a b less?)
  466. takes two lists a and b such that (sorted? a less?) and (sorted? b less?)
  467. and returns a new list in which the elements of a and b have been stably
  468. interleaved so that (sorted? (merge a b less?) less?).
  469. Note: this does _not_ accept vectors. */
  470. SCM_DEFINE (scm_merge, "merge", 3, 0, 0,
  471. (SCM alist, SCM blist, SCM less),
  472. "")
  473. #define FUNC_NAME s_scm_merge
  474. {
  475. long alen, blen; /* list lengths */
  476. SCM build, last;
  477. cmp_fun_t cmp = scm_cmp_function (less);
  478. SCM_VALIDATE_NIM (3,less);
  479. if (SCM_NULLP (alist))
  480. return blist;
  481. else if (SCM_NULLP (blist))
  482. return alist;
  483. else
  484. {
  485. SCM_VALIDATE_NONEMPTYLIST_COPYLEN (1,alist,alen);
  486. SCM_VALIDATE_NONEMPTYLIST_COPYLEN (2,blist,blen);
  487. if ((*cmp) (less, SCM_CARLOC (blist), SCM_CARLOC (alist)))
  488. {
  489. build = scm_cons (SCM_CAR (blist), SCM_EOL);
  490. blist = SCM_CDR (blist);
  491. blen--;
  492. }
  493. else
  494. {
  495. build = scm_cons (SCM_CAR (alist), SCM_EOL);
  496. alist = SCM_CDR (alist);
  497. alen--;
  498. }
  499. last = build;
  500. while ((alen > 0) && (blen > 0))
  501. {
  502. if ((*cmp) (less, SCM_CARLOC (blist), SCM_CARLOC (alist)))
  503. {
  504. SCM_SETCDR (last, scm_cons (SCM_CAR (blist), SCM_EOL));
  505. blist = SCM_CDR (blist);
  506. blen--;
  507. }
  508. else
  509. {
  510. SCM_SETCDR (last, scm_cons (SCM_CAR (alist), SCM_EOL));
  511. alist = SCM_CDR (alist);
  512. alen--;
  513. }
  514. last = SCM_CDR (last);
  515. }
  516. if ((alen > 0) && (blen == 0))
  517. SCM_SETCDR (last, alist);
  518. else if ((alen == 0) && (blen > 0))
  519. SCM_SETCDR (last, blist);
  520. }
  521. return build;
  522. }
  523. #undef FUNC_NAME
  524. static SCM
  525. scm_merge_list_x (SCM alist, SCM blist,
  526. long alen, long blen,
  527. cmp_fun_t cmp, SCM less)
  528. {
  529. SCM build, last;
  530. if (SCM_NULLP (alist))
  531. return blist;
  532. else if (SCM_NULLP (blist))
  533. return alist;
  534. else
  535. {
  536. if ((*cmp) (less, SCM_CARLOC (blist), SCM_CARLOC (alist)))
  537. {
  538. build = blist;
  539. blist = SCM_CDR (blist);
  540. blen--;
  541. }
  542. else
  543. {
  544. build = alist;
  545. alist = SCM_CDR (alist);
  546. alen--;
  547. }
  548. last = build;
  549. while ((alen > 0) && (blen > 0))
  550. {
  551. if ((*cmp) (less, SCM_CARLOC (blist), SCM_CARLOC (alist)))
  552. {
  553. SCM_SETCDR (last, blist);
  554. blist = SCM_CDR (blist);
  555. blen--;
  556. }
  557. else
  558. {
  559. SCM_SETCDR (last, alist);
  560. alist = SCM_CDR (alist);
  561. alen--;
  562. }
  563. last = SCM_CDR (last);
  564. }
  565. if ((alen > 0) && (blen == 0))
  566. SCM_SETCDR (last, alist);
  567. else if ((alen == 0) && (blen > 0))
  568. SCM_SETCDR (last, blist);
  569. }
  570. return build;
  571. } /* scm_merge_list_x */
  572. SCM_DEFINE (scm_merge_x, "merge!", 3, 0, 0,
  573. (SCM alist, SCM blist, SCM less),
  574. "")
  575. #define FUNC_NAME s_scm_merge_x
  576. {
  577. long alen, blen; /* list lengths */
  578. SCM_VALIDATE_NIM (3,less);
  579. if (SCM_NULLP (alist))
  580. return blist;
  581. else if (SCM_NULLP (blist))
  582. return alist;
  583. else
  584. {
  585. SCM_VALIDATE_NONEMPTYLIST_COPYLEN (1,alist,alen);
  586. SCM_VALIDATE_NONEMPTYLIST_COPYLEN (2,blist,blen);
  587. return scm_merge_list_x (alist, blist,
  588. alen, blen,
  589. scm_cmp_function (less),
  590. less);
  591. }
  592. }
  593. #undef FUNC_NAME
  594. /* This merge sort algorithm is same as slib's by Richard A. O'Keefe.
  595. The algorithm is stable. We also tried to use the algorithm used by
  596. scsh's merge-sort but that algorithm showed to not be stable, even
  597. though it claimed to be.
  598. */
  599. static SCM
  600. scm_merge_list_step (SCM * seq,
  601. cmp_fun_t cmp,
  602. SCM less,
  603. int n)
  604. {
  605. SCM a, b;
  606. if (n > 2)
  607. {
  608. long mid = n / 2;
  609. a = scm_merge_list_step (seq, cmp, less, mid);
  610. b = scm_merge_list_step (seq, cmp, less, n - mid);
  611. return scm_merge_list_x (a, b, mid, n - mid, cmp, less);
  612. }
  613. else if (n == 2)
  614. {
  615. SCM p = *seq;
  616. SCM rest = SCM_CDR (*seq);
  617. SCM x = SCM_CAR (*seq);
  618. SCM y = SCM_CAR (SCM_CDR (*seq));
  619. *seq = SCM_CDR (rest);
  620. SCM_SETCDR (rest, SCM_EOL);
  621. if ((*cmp) (less, &y, &x))
  622. {
  623. SCM_SETCAR (p, y);
  624. SCM_SETCAR (rest, x);
  625. }
  626. return p;
  627. }
  628. else if (n == 1)
  629. {
  630. SCM p = *seq;
  631. *seq = SCM_CDR (p);
  632. SCM_SETCDR (p, SCM_EOL);
  633. return p;
  634. }
  635. else
  636. return SCM_EOL;
  637. } /* scm_merge_list_step */
  638. /* scm_sort_x manages lists and vectors, not stable sort */
  639. SCM_DEFINE (scm_sort_x, "sort!", 2, 0, 0,
  640. (SCM items, SCM less),
  641. "")
  642. #define FUNC_NAME s_scm_sort_x
  643. {
  644. long len; /* list/vector length */
  645. if (SCM_NULLP(items))
  646. return SCM_EOL;
  647. SCM_VALIDATE_NIM (1,items);
  648. SCM_VALIDATE_NIM (2,less);
  649. if (SCM_CONSP (items))
  650. {
  651. SCM_VALIDATE_LIST_COPYLEN (1,items,len);
  652. return scm_merge_list_step (&items, scm_cmp_function (less), less, len);
  653. }
  654. else if (SCM_VECTORP (items))
  655. {
  656. len = SCM_LENGTH (items);
  657. scm_restricted_vector_sort_x (items,
  658. less,
  659. SCM_MAKINUM (0L),
  660. SCM_MAKINUM (len));
  661. return items;
  662. }
  663. else
  664. RETURN_SCM_WTA (1,items);
  665. }
  666. #undef FUNC_NAME
  667. /* scm_sort manages lists and vectors, not stable sort */
  668. SCM_DEFINE (scm_sort, "sort", 2, 0, 0,
  669. (SCM items, SCM less),
  670. "")
  671. #define FUNC_NAME s_scm_sort
  672. {
  673. SCM sortvec; /* the vector we actually sort */
  674. long len; /* list/vector length */
  675. if (SCM_NULLP(items))
  676. return SCM_EOL;
  677. SCM_VALIDATE_NIM (1,items);
  678. SCM_VALIDATE_NIM (2,less);
  679. if (SCM_CONSP (items))
  680. {
  681. SCM_VALIDATE_LIST_COPYLEN (1,items,len);
  682. items = scm_list_copy (items);
  683. return scm_merge_list_step (&items, scm_cmp_function (less), less, len);
  684. }
  685. #ifdef HAVE_ARRAYS
  686. /* support ordinary vectors even if arrays not available? */
  687. else if (SCM_VECTORP (items))
  688. {
  689. len = SCM_LENGTH (items);
  690. sortvec = scm_make_uve (len, scm_array_prototype (items));
  691. scm_array_copy_x (items, sortvec);
  692. scm_restricted_vector_sort_x (sortvec,
  693. less,
  694. SCM_MAKINUM (0L),
  695. SCM_MAKINUM (len));
  696. return sortvec;
  697. }
  698. #endif
  699. else
  700. RETURN_SCM_WTA (1,items);
  701. }
  702. #undef FUNC_NAME
  703. static void
  704. scm_merge_vector_x (void *const vecbase,
  705. void *const tempbase,
  706. cmp_fun_t cmp,
  707. SCM less,
  708. long low,
  709. long mid,
  710. long high)
  711. {
  712. register SCM *vp = (SCM *) vecbase;
  713. register SCM *temp = (SCM *) tempbase;
  714. long it; /* Index for temp vector */
  715. long i1 = low; /* Index for lower vector segment */
  716. long i2 = mid + 1; /* Index for upper vector segment */
  717. /* Copy while both segments contain more characters */
  718. for (it = low; (i1 <= mid) && (i2 <= high); ++it)
  719. if ((*cmp) (less, &vp[i2], &vp[i1]))
  720. temp[it] = vp[i2++];
  721. else
  722. temp[it] = vp[i1++];
  723. /* Copy while first segment contains more characters */
  724. while (i1 <= mid)
  725. temp[it++] = vp[i1++];
  726. /* Copy while second segment contains more characters */
  727. while (i2 <= high)
  728. temp[it++] = vp[i2++];
  729. /* Copy back from temp to vp */
  730. for (it = low; it <= high; ++it)
  731. vp[it] = temp[it];
  732. } /* scm_merge_vector_x */
  733. static void
  734. scm_merge_vector_step (void *const vp,
  735. void *const temp,
  736. cmp_fun_t cmp,
  737. SCM less,
  738. long low,
  739. long high)
  740. {
  741. if (high > low)
  742. {
  743. long mid = (low + high) / 2;
  744. scm_merge_vector_step (vp, temp, cmp, less, low, mid);
  745. scm_merge_vector_step (vp, temp, cmp, less, mid+1, high);
  746. scm_merge_vector_x (vp, temp, cmp, less, low, mid, high);
  747. }
  748. } /* scm_merge_vector_step */
  749. /* stable-sort! manages lists and vectors */
  750. SCM_DEFINE (scm_stable_sort_x, "stable-sort!", 2, 0, 0,
  751. (SCM items, SCM less),
  752. "")
  753. #define FUNC_NAME s_scm_stable_sort_x
  754. {
  755. long len; /* list/vector length */
  756. if (SCM_NULLP (items))
  757. return SCM_EOL;
  758. SCM_VALIDATE_NIM (1,items);
  759. SCM_VALIDATE_NIM (2,less);
  760. if (SCM_CONSP (items))
  761. {
  762. SCM_VALIDATE_LIST_COPYLEN (1,items,len);
  763. return scm_merge_list_step (&items, scm_cmp_function (less), less, len);
  764. }
  765. else if (SCM_VECTORP (items))
  766. {
  767. SCM *temp, *vp;
  768. len = SCM_LENGTH (items);
  769. temp = malloc (len * sizeof(SCM));
  770. vp = SCM_VELTS (items);
  771. scm_merge_vector_step (vp,
  772. temp,
  773. scm_cmp_function (less),
  774. less,
  775. 0,
  776. len - 1);
  777. free(temp);
  778. return items;
  779. }
  780. else
  781. RETURN_SCM_WTA (1,items);
  782. }
  783. #undef FUNC_NAME
  784. /* stable_sort manages lists and vectors */
  785. SCM_DEFINE (scm_stable_sort, "stable-sort", 2, 0, 0,
  786. (SCM items, SCM less),
  787. "")
  788. #define FUNC_NAME s_scm_stable_sort
  789. {
  790. long len; /* list/vector length */
  791. if (SCM_NULLP (items))
  792. return SCM_EOL;
  793. SCM_VALIDATE_NIM (1,items);
  794. SCM_VALIDATE_NIM (2,less);
  795. if (SCM_CONSP (items))
  796. {
  797. SCM_VALIDATE_LIST_COPYLEN (1,items,len);
  798. items = scm_list_copy (items);
  799. return scm_merge_list_step (&items, scm_cmp_function (less), less, len);
  800. }
  801. #ifdef HAVE_ARRAYS
  802. /* support ordinary vectors even if arrays not available? */
  803. else if (SCM_VECTORP (items))
  804. {
  805. SCM retvec;
  806. SCM *temp, *vp;
  807. len = SCM_LENGTH (items);
  808. retvec = scm_make_uve (len, scm_array_prototype (items));
  809. scm_array_copy_x (items, retvec);
  810. temp = malloc (len * sizeof (SCM));
  811. vp = SCM_VELTS (retvec);
  812. scm_merge_vector_step (vp,
  813. temp,
  814. scm_cmp_function (less),
  815. less,
  816. 0,
  817. len - 1);
  818. free (temp);
  819. return retvec;
  820. }
  821. #endif
  822. else
  823. RETURN_SCM_WTA (1,items);
  824. }
  825. #undef FUNC_NAME
  826. /* stable */
  827. SCM_DEFINE (scm_sort_list_x, "sort-list!", 2, 0, 0,
  828. (SCM items, SCM less),
  829. "")
  830. #define FUNC_NAME s_scm_sort_list_x
  831. {
  832. long len;
  833. SCM_VALIDATE_LIST_COPYLEN (1,items,len);
  834. SCM_VALIDATE_NIM (2,less);
  835. return scm_merge_list_step (&items, scm_cmp_function (less), less, len);
  836. }
  837. #undef FUNC_NAME
  838. /* stable */
  839. SCM_DEFINE (scm_sort_list, "sort-list", 2, 0, 0,
  840. (SCM items, SCM less),
  841. "")
  842. #define FUNC_NAME s_scm_sort_list
  843. {
  844. long len;
  845. SCM_VALIDATE_LIST_COPYLEN (1,items,len);
  846. SCM_VALIDATE_NIM (2,less);
  847. items = scm_list_copy (items);
  848. return scm_merge_list_step (&items, scm_cmp_function (less), less, len);
  849. }
  850. #undef FUNC_NAME
  851. void
  852. scm_init_sort ()
  853. {
  854. #include "libguile/sort.x"
  855. scm_add_feature ("sort");
  856. }
  857. /*
  858. Local Variables:
  859. c-file-style: "gnu"
  860. End:
  861. */