3 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
12 (in-package "SB!IMPL")
14 (defun sort-vector (vector start end predicate-fun key-fun-or-nil
)
15 (sort-vector vector start end predicate-fun key-fun-or-nil
))
17 ;;; This is MAYBE-INLINE because it's not too hard to have an
18 ;;; application where sorting is a major bottleneck, and inlining it
19 ;;; allows the compiler to make enough optimizations that it might be
20 ;;; worth the (large) cost in space.
21 (declaim (maybe-inline sort stable-sort
))
22 (defun sort (sequence predicate
&rest args
&key key
)
24 "Destructively sort SEQUENCE. PREDICATE should return non-NIL if
25 ARG1 is to precede ARG2."
26 (declare (truly-dynamic-extent args
))
27 (let ((predicate-fun (%coerce-callable-to-fun predicate
)))
28 (seq-dispatch sequence
29 (stable-sort-list sequence
31 (if key
(%coerce-callable-to-fun key
) #'identity
))
32 (let ((key-fun-or-nil (and key
(%coerce-callable-to-fun key
))))
33 (with-array-data ((vector (the vector sequence
))
36 :check-fill-pointer t
)
37 (sort-vector vector start end predicate-fun key-fun-or-nil
))
39 (apply #'sb
!sequence
:sort sequence predicate args
))))
42 (defun stable-sort (sequence predicate
&rest args
&key key
)
44 "Destructively sort SEQUENCE. PREDICATE should return non-NIL if
45 ARG1 is to precede ARG2."
46 (declare (truly-dynamic-extent args
))
47 (let ((predicate-fun (%coerce-callable-to-fun predicate
)))
48 (seq-dispatch sequence
49 (stable-sort-list sequence
51 (if key
(%coerce-callable-to-fun key
) #'identity
))
52 (if (typep sequence
'simple-vector
)
53 (stable-sort-simple-vector sequence
55 (and key
(%coerce-callable-to-fun key
)))
56 (stable-sort-vector sequence
58 (and key
(%coerce-callable-to-fun key
))))
59 (apply #'sb
!sequence
:stable-sort sequence predicate args
))))
61 ;;; FUNCALL-USING-KEY saves us a function call sometimes.
62 (eval-when (:compile-toplevel
:execute
)
63 (sb!xc
:defmacro funcall2-using-key
(pred key one two
)
65 (funcall ,pred
(funcall ,key
,one
)
67 (funcall ,pred
,one
,two
)))
70 ;;;; stable sort of lists
71 (declaim (maybe-inline merge-lists
* stable-sort-list
))
73 ;;; Destructively merge LIST-1 with LIST-2 (given that they're already
74 ;;; sorted w.r.t. PRED-FUN on KEY-FUN, giving output sorted the same
75 ;;; way). In the resulting list, elements of LIST-1 are guaranteed to
76 ;;; come before equal elements of LIST-2.
78 ;;; Enqueues the values in the right order in HEAD's cdr, and returns
80 (defun merge-lists* (head list1 list2 test key
&aux
(tail head
))
81 (declare (type cons head list1 list2
)
82 (type function test key
)
84 (let ((key1 (funcall key
(car list1
)))
85 (key2 (funcall key
(car list2
))))
86 (macrolet ((merge-one (l1 k1 l2
)
90 (let ((rest (cdr ,l1
)))
93 ,k1
(funcall key
(first rest
))))
96 (return (cdr head
))))))))
98 (if (funcall test key2
; this way, equivalent
99 key1
) ; values are first popped
100 (merge-one list2 key2 list1
) ; from list1
101 (merge-one list1 key1 list2
))))))
103 ;;; Convenience wrapper for CL:MERGE
104 (declaim (inline merge-lists
))
105 (defun merge-lists (list1 list2 test key
)
111 (let ((head (cons nil nil
)))
112 (declare (dynamic-extent head
))
113 (merge-lists* head list1 list2 test key
)))))
115 ;;; Small specialised stable sorts
116 (declaim (inline stable-sort-list-2 stable-sort-list-3
))
117 (defun stable-sort-list-2 (list test key
)
118 (declare (type cons list
)
119 (type function test key
))
120 (let ((second (cdr list
)))
121 (declare (type cons second
))
122 (when (funcall test
(funcall key
(car second
))
123 (funcall key
(car list
)))
124 (rotatef (car list
) (car second
)))
125 (values list second
(shiftf (cdr second
) nil
))))
127 (defun stable-sort-list-3 (list test key
)
128 (declare (type cons list
)
129 (type function test key
))
130 (let* ((second (cdr list
))
135 (declare (type cons second third
))
136 (when (funcall test
(funcall key y
)
139 (let ((key-z (funcall key z
)))
140 (when (funcall test key-z
142 (if (funcall test key-z
149 (values list third
(shiftf (cdr third
) nil
))))
151 ;;; STABLE-SORT-LIST implements a top-down merge sort. See the closest
152 ;;; intro to algorithms book. Benchmarks have shown significantly
153 ;;; improved performance over the previous (hairier) bottom-up
154 ;;; implementation, particularly on non-power-of-two sizes: bottom-up
155 ;;; recursed on power-of-two-sized subsequences, which can result in
156 ;;; very unbalanced recursion trees.
158 ;;; The minimum length at which list merge sort will try and detect
159 ;;; it can merge disjoint ranges (e.g. sorted inputs) in constant time.
160 (defconstant +stable-sort-fast-merge-limit
+ 8)
162 (defun stable-sort-list (list test key
&aux
(head (cons :head list
)))
163 (declare (type list list
)
164 (type function test key
)
165 (dynamic-extent head
))
166 (labels ((merge* (size list1 tail1 list2 tail2 rest
)
167 (declare (optimize speed
)
168 (type (and fixnum unsigned-byte
) size
)
169 (type cons list1 tail1 list2 tail2
))
170 (when (>= size
+stable-sort-fast-merge-limit
+)
171 (cond ((not (funcall test
(funcall key
(car list2
)) ; stability
172 (funcall key
(car tail1
)))) ; trickery
173 (setf (cdr tail1
) list2
)
174 (return-from merge
* (values list1 tail2 rest
)))
175 ((funcall test
(funcall key
(car tail2
))
176 (funcall key
(car list1
)))
177 (setf (cdr tail2
) list1
)
178 (return-from merge
* (values list2 tail1 rest
)))))
179 (values (merge-lists* head list1 list2 test key
)
180 (if (null (cdr tail1
))
185 (declare (optimize speed
)
187 (type (and fixnum unsigned-byte
) size
))
189 (let ((half (ash size -
1)))
190 (multiple-value-bind (list1 tail1 rest
)
192 (multiple-value-bind (list2 tail2 rest
)
193 (recur rest
(- size half
))
194 (merge* size list1 tail1 list2 tail2 rest
)))))
196 (stable-sort-list-3 list test key
))
198 (stable-sort-list-2 list test key
))
200 (values list list
(shiftf (cdr list
) nil
))))))
202 (values (recur list
(length list
))))))
204 ;;;; stable sort of vectors
206 ;;; Stable sorting vectors is done with the same algorithm used for
207 ;;; lists, using a temporary vector to merge back and forth between it
208 ;;; and the given vector to sort.
210 (eval-when (:compile-toplevel
:execute
)
212 ;;; STABLE-SORT-MERGE-VECTORS* takes a source vector with subsequences,
213 ;;; start-1 (inclusive) ... end-1 (exclusive) and
214 ;;; end-1 (inclusive) ... end-2 (exclusive),
215 ;;; and merges them into a target vector starting at index start-1.
217 (sb!xc
:defmacro stable-sort-merge-vectors
* (source target start-1 end-1 end-2
224 (,j
,end-1
) ; start-2
225 (,target-i
,start-1
))
226 (declare (fixnum ,i
,j
,target-i
))
229 (loop (if (= ,j
,end-2
) (return))
230 (setf (,target-ref
,target
,target-i
)
231 (,source-ref
,source
,j
))
236 (loop (if (= ,i
,end-1
) (return))
237 (setf (,target-ref
,target
,target-i
)
238 (,source-ref
,source
,i
))
242 ((funcall2-using-key ,pred
,key
243 (,source-ref
,source
,j
)
244 (,source-ref
,source
,i
))
245 (setf (,target-ref
,target
,target-i
)
246 (,source-ref
,source
,j
))
248 (t (setf (,target-ref
,target
,target-i
)
249 (,source-ref
,source
,i
))
253 ;;; VECTOR-MERGE-SORT is the same algorithm used to stable sort lists,
254 ;;; but it uses a temporary vector. DIRECTION determines whether we
255 ;;; are merging into the temporary (T) or back into the given vector
257 (sb!xc
:defmacro vector-merge-sort
(vector pred key vector-ref
)
259 (vector-len n direction unsorted start-1 end-1 end-2 temp i
)
260 `(let* ((,vector-len
(length (the vector
,vector
)))
261 (,n
1) ; bottom-up size of contiguous runs to be merged
262 (,direction t
) ; t vector --> temp nil temp --> vector
263 (,temp
(make-array ,vector-len
))
264 (,unsorted
0) ; unsorted..vector-len are the elements that need
265 ; to be merged for a given n
266 (,start-1
0)) ; one n-len subsequence to be merged with the next
267 (declare (fixnum ,vector-len
,n
,unsorted
,start-1
)
268 (simple-vector ,temp
))
270 ;; for each n, we start taking n-runs from the start of the vector
273 (setf ,start-1
,unsorted
)
274 (let ((,end-1
(+ ,start-1
,n
)))
275 (declare (fixnum ,end-1
))
276 (cond ((< ,end-1
,vector-len
)
277 ;; there are enough elements for a second run
278 (let ((,end-2
(+ ,end-1
,n
)))
279 (declare (fixnum ,end-2
))
280 (if (> ,end-2
,vector-len
) (setf ,end-2
,vector-len
))
281 (setf ,unsorted
,end-2
)
283 (stable-sort-merge-vectors*
285 ,start-1
,end-1
,end-2
,pred
,key
,vector-ref svref
)
286 (stable-sort-merge-vectors*
288 ,start-1
,end-1
,end-2
,pred
,key svref
,vector-ref
))
289 (if (= ,unsorted
,vector-len
) (return))))
290 ;; if there is only one run, copy those elements to the end
292 (do ((,i
,start-1
(1+ ,i
)))
294 (declare (fixnum ,i
))
295 (setf (svref ,temp
,i
) (,vector-ref
,vector
,i
)))
296 (do ((,i
,start-1
(1+ ,i
)))
298 (declare (fixnum ,i
))
299 (setf (,vector-ref
,vector
,i
) (svref ,temp
,i
))))
301 ;; If the inner loop only executed once, then there were only enough
302 ;; elements for two subsequences given n, so all the elements have
303 ;; been merged into one list. Start-1 will have remained 0 upon exit.
304 (when (zerop ,start-1
)
306 ;; if we just merged into the temporary, copy it all back
307 ;; to the given vector.
308 (dotimes (,i
,vector-len
)
309 (setf (,vector-ref
,vector
,i
) (svref ,temp
,i
))))
310 ;; Kill the new vector to prevent garbage from being retained.
311 (%shrink-vector
,temp
0)
313 (setf ,n
(ash ,n
1)) ; (* 2 n)
314 (setf ,direction
(not ,direction
))))))
318 (defun stable-sort-simple-vector (vector pred key
)
319 (declare (type simple-vector vector
)
321 (type (or null function
) key
))
322 (vector-merge-sort vector pred key svref
))
324 (defun stable-sort-vector (vector pred key
)
325 (declare (type function pred
)
326 (type (or null function
) key
))
327 (vector-merge-sort vector pred key aref
))
331 (eval-when (:compile-toplevel
:execute
)
333 ;;; MERGE-VECTORS returns a new vector which contains an interleaving
334 ;;; of the elements of VECTOR-1 and VECTOR-2. Elements from VECTOR-2
335 ;;; are chosen only if they are strictly less than elements of
336 ;;; VECTOR-1, (PRED ELT-2 ELT-1), as specified in the manual.
337 (sb!xc
:defmacro merge-vectors
(vector-1 length-1 vector-2 length-2
338 result-vector pred key access
)
339 (let ((result-i (gensym))
342 `(let* ((,result-i
0)
345 (declare (fixnum ,result-i
,i
,j
))
347 (cond ((= ,i
,length-1
)
348 (loop (if (= ,j
,length-2
) (return))
349 (setf (,access
,result-vector
,result-i
)
350 (,access
,vector-2
,j
))
353 (return ,result-vector
))
355 (loop (if (= ,i
,length-1
) (return))
356 (setf (,access
,result-vector
,result-i
)
357 (,access
,vector-1
,i
))
360 (return ,result-vector
))
361 ((funcall2-using-key ,pred
,key
362 (,access
,vector-2
,j
) (,access
,vector-1
,i
))
363 (setf (,access
,result-vector
,result-i
)
364 (,access
,vector-2
,j
))
366 (t (setf (,access
,result-vector
,result-i
)
367 (,access
,vector-1
,i
))
373 (defun merge (result-type sequence1 sequence2 predicate
&key key
)
375 "Merge the sequences SEQUENCE1 and SEQUENCE2 destructively into a
376 sequence of type RESULT-TYPE using PREDICATE to order the elements."
377 ;; FIXME: This implementation is remarkably inefficient in various
378 ;; ways. In decreasing order of estimated user astonishment, I note:
379 ;; full calls to SPECIFIER-TYPE at runtime; copying input vectors
380 ;; to lists before doing MERGE-LISTS -- WHN 2003-01-05
381 (let ((type (specifier-type result-type
))
382 (pred-fun (%coerce-callable-to-fun predicate
))
383 ;; Avoid coercing NIL to a function since 2 out of 3 branches of the
384 ;; COND below optimize for NIL as the key function. Additionally
385 ;; recognize the reverse - when you said #'IDENTITY which can be
386 ;; turned into NIL. Also, in the generic case, don't defer a
387 ;; type error to the method (even though it also coerces to fun).
388 (key-fun (when (and key
(neq key
#'identity
))
389 (%coerce-callable-to-fun key
))))
391 ((csubtypep type
(specifier-type 'list
))
392 ;; the VECTOR clause, below, goes through MAKE-SEQUENCE, so
393 ;; benefits from the error checking there. Short of
394 ;; reimplementing everything, we can't do the same for the LIST
395 ;; case, so do relevant length checking here:
396 (let ((s1 (coerce sequence1
'list
))
397 (s2 (coerce sequence2
'list
))
398 ;; MERGE-LISTS* does not contain special code for KEY = NIL.
399 (key-fun (or key-fun
#'identity
)))
400 (when (type= type
(specifier-type 'list
))
401 (return-from merge
(merge-lists s1 s2 pred-fun key-fun
)))
402 (when (eq type
*empty-type
*)
403 (bad-sequence-type-error nil
))
404 (when (type= type
(specifier-type 'null
))
405 (if (and (null s1
) (null s2
))
406 (return-from merge
'nil
)
407 ;; FIXME: This will break on circular lists (as,
408 ;; indeed, will the whole MERGE function).
409 (sequence-type-length-mismatch-error type
412 (if (cons-type-p type
)
413 (multiple-value-bind (min exactp
)
414 (sb!kernel
::cons-type-length-info type
)
415 (let ((length (+ (length s1
) (length s2
))))
417 (unless (= length min
)
418 (sequence-type-length-mismatch-error type length
))
419 (unless (>= length min
)
420 (sequence-type-length-mismatch-error type length
)))
421 (merge-lists s1 s2 pred-fun key-fun
)))
422 (sequence-type-too-hairy result-type
))))
423 ((csubtypep type
(specifier-type 'vector
))
424 (let* ((vector-1 (coerce sequence1
'vector
))
425 (vector-2 (coerce sequence2
'vector
))
426 (length-1 (length vector-1
))
427 (length-2 (length vector-2
))
428 (result (make-sequence result-type
(+ length-1 length-2
))))
429 (declare (vector vector-1 vector-2
) ; FIXME: this looks redundant,
430 (fixnum length-1 length-2
)) ; as does this.
431 (if (and (simple-vector-p result
)
432 (simple-vector-p vector-1
)
433 (simple-vector-p vector-2
))
434 (merge-vectors vector-1 length-1 vector-2 length-2
435 result pred-fun key-fun svref
)
436 ;; Some things that could improve the fancy vector case:
437 ;; - recognize when the only fancy aspect of both inputs
438 ;; is that they have fill pointers.
439 ;; - use the specialized reffer for inputs + output
440 (merge-vectors vector-1 length-1 vector-2 length-2
441 result pred-fun key-fun aref
))))
442 ((and (csubtypep type
(specifier-type 'sequence
))
443 (awhen (find-class result-type nil
)
445 (sb!mop
:class-prototype
(sb!pcl
:ensure-class-finalized it
))
446 ;; GF dispatch deals with the erroneous situation wherein
447 ;; either of SEQUENCE1 or SEQUENCE2 is not a sequence.
448 ;; Note that the one builtin method optimizes for NIL as
449 ;; the key fun, and we correctly preserve a NIL here.
450 sequence1 sequence2 pred-fun
:key key-fun
))))
451 (t (bad-sequence-type-error result-type
)))))