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