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