MERGE calls SB-SEQUENCE:MERGE for extended sequences
[sbcl.git] / src / code / sort.lisp
blob14bc87a2d49309c0d74f01013d2ec3330ca7bc5c
1 ;;;; SORT and friends
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
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)
23 #!+sb-doc
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
30 predicate-fun
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))
34 (start)
35 (end)
36 :check-fill-pointer t)
37 (sort-vector vector start end predicate-fun key-fun-or-nil))
38 sequence)
39 (apply #'sb!sequence:sort sequence predicate args))))
41 ;;;; stable sorting
42 (defun stable-sort (sequence predicate &rest args &key key)
43 #!+sb-doc
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
50 predicate-fun
51 (if key (%coerce-callable-to-fun key) #'identity))
52 (if (typep sequence 'simple-vector)
53 (stable-sort-simple-vector sequence
54 predicate-fun
55 (and key (%coerce-callable-to-fun key)))
56 (stable-sort-vector sequence
57 predicate-fun
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)
64 `(if ,key
65 (funcall ,pred (funcall ,key ,one)
66 (funcall ,key ,two))
67 (funcall ,pred ,one ,two)))
68 ) ; EVAL-WHEN
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.
77 ;;;
78 ;;; Enqueues the values in the right order in HEAD's cdr, and returns
79 ;;; the merged list.
80 (defun merge-lists* (head list1 list2 test key &aux (tail head))
81 (declare (type cons head list1 list2)
82 (type function test key)
83 (optimize speed))
84 (let ((key1 (funcall key (car list1)))
85 (key2 (funcall key (car list2))))
86 (macrolet ((merge-one (l1 k1 l2)
87 `(progn
88 (setf (cdr tail) ,l1
89 tail ,l1)
90 (let ((rest (cdr ,l1)))
91 (cond (rest
92 (setf ,l1 rest
93 ,k1 (funcall key (first rest))))
95 (setf (cdr ,l1) ,l2)
96 (return (cdr head))))))))
97 (loop
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)
106 (cond ((null list1)
107 list2)
108 ((null list2)
109 list1)
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))
131 (third (cdr second))
132 (x (car list))
133 (y (car second))
134 (z (car third)))
135 (declare (type cons second third))
136 (when (funcall test (funcall key y)
137 (funcall key x))
138 (rotatef x y))
139 (let ((key-z (funcall key z)))
140 (when (funcall test key-z
141 (funcall key y))
142 (if (funcall test key-z
143 (funcall key x))
144 (rotatef x z y)
145 (rotatef z y))))
146 (setf (car list) x
147 (car second) y
148 (car third) 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))
181 tail1
182 tail2)
183 rest))
184 (recur (list size)
185 (declare (optimize speed)
186 (type cons list)
187 (type (and fixnum unsigned-byte) size))
188 (cond ((> size 3)
189 (let ((half (ash size -1)))
190 (multiple-value-bind (list1 tail1 rest)
191 (recur list half)
192 (multiple-value-bind (list2 tail2 rest)
193 (recur rest (- size half))
194 (merge* size list1 tail1 list2 tail2 rest)))))
195 ((= size 3)
196 (stable-sort-list-3 list test key))
197 ((= size 2)
198 (stable-sort-list-2 list test key))
199 (t ; (= size 1)
200 (values list list (shiftf (cdr list) nil))))))
201 (when list
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
218 pred key source-ref
219 target-ref)
220 (let ((i (gensym))
221 (j (gensym))
222 (target-i (gensym)))
223 `(let ((,i ,start-1)
224 (,j ,end-1) ; start-2
225 (,target-i ,start-1))
226 (declare (fixnum ,i ,j ,target-i))
227 (loop
228 (cond ((= ,i ,end-1)
229 (loop (if (= ,j ,end-2) (return))
230 (setf (,target-ref ,target ,target-i)
231 (,source-ref ,source ,j))
232 (incf ,target-i)
233 (incf ,j))
234 (return))
235 ((= ,j ,end-2)
236 (loop (if (= ,i ,end-1) (return))
237 (setf (,target-ref ,target ,target-i)
238 (,source-ref ,source ,i))
239 (incf ,target-i)
240 (incf ,i))
241 (return))
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))
247 (incf ,j))
248 (t (setf (,target-ref ,target ,target-i)
249 (,source-ref ,source ,i))
250 (incf ,i)))
251 (incf ,target-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
256 ;;; (NIL).
257 (sb!xc:defmacro vector-merge-sort (vector pred key vector-ref)
258 (with-unique-names
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))
269 (loop
270 ;; for each n, we start taking n-runs from the start of the vector
271 (setf ,unsorted 0)
272 (loop
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)
282 (if ,direction
283 (stable-sort-merge-vectors*
284 ,vector ,temp
285 ,start-1 ,end-1 ,end-2 ,pred ,key ,vector-ref svref)
286 (stable-sort-merge-vectors*
287 ,temp ,vector
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
291 (t (if ,direction
292 (do ((,i ,start-1 (1+ ,i)))
293 ((= ,i ,vector-len))
294 (declare (fixnum ,i))
295 (setf (svref ,temp ,i) (,vector-ref ,vector ,i)))
296 (do ((,i ,start-1 (1+ ,i)))
297 ((= ,i ,vector-len))
298 (declare (fixnum ,i))
299 (setf (,vector-ref ,vector ,i) (svref ,temp ,i))))
300 (return)))))
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)
305 (when ,direction
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)
312 (return ,vector))
313 (setf ,n (ash ,n 1)) ; (* 2 n)
314 (setf ,direction (not ,direction))))))
316 ) ; EVAL-when
318 (defun stable-sort-simple-vector (vector pred key)
319 (declare (type simple-vector vector)
320 (type function pred)
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))
329 ;;;; merging
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))
340 (i (gensym))
341 (j (gensym)))
342 `(let* ((,result-i 0)
343 (,i 0)
344 (,j 0))
345 (declare (fixnum ,result-i ,i ,j))
346 (loop
347 (cond ((= ,i ,length-1)
348 (loop (if (= ,j ,length-2) (return))
349 (setf (,access ,result-vector ,result-i)
350 (,access ,vector-2 ,j))
351 (incf ,result-i)
352 (incf ,j))
353 (return ,result-vector))
354 ((= ,j ,length-2)
355 (loop (if (= ,i ,length-1) (return))
356 (setf (,access ,result-vector ,result-i)
357 (,access ,vector-1 ,i))
358 (incf ,result-i)
359 (incf ,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))
365 (incf ,j))
366 (t (setf (,access ,result-vector ,result-i)
367 (,access ,vector-1 ,i))
368 (incf ,i)))
369 (incf ,result-i)))))
371 ) ; EVAL-WHEN
373 (defun merge (result-type sequence1 sequence2 predicate &key key)
374 #!+sb-doc
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 (cond
383 ((csubtypep type (specifier-type 'list))
384 ;; the VECTOR clause, below, goes through MAKE-SEQUENCE, so
385 ;; benefits from the error checking there. Short of
386 ;; reimplementing everything, we can't do the same for the LIST
387 ;; case, so do relevant length checking here:
388 (let ((s1 (coerce sequence1 'list))
389 (s2 (coerce sequence2 'list))
390 (pred-fun (%coerce-callable-to-fun predicate))
391 (key-fun (if key
392 (%coerce-callable-to-fun key)
393 #'identity)))
394 (when (type= type (specifier-type 'list))
395 (return-from merge (merge-lists s1 s2 pred-fun key-fun)))
396 (when (eq type *empty-type*)
397 (bad-sequence-type-error nil))
398 (when (type= type (specifier-type 'null))
399 (if (and (null s1) (null s2))
400 (return-from merge 'nil)
401 ;; FIXME: This will break on circular lists (as,
402 ;; indeed, will the whole MERGE function).
403 (sequence-type-length-mismatch-error type
404 (+ (length s1)
405 (length s2)))))
406 (if (cons-type-p type)
407 (multiple-value-bind (min exactp)
408 (sb!kernel::cons-type-length-info type)
409 (let ((length (+ (length s1) (length s2))))
410 (if exactp
411 (unless (= length min)
412 (sequence-type-length-mismatch-error type length))
413 (unless (>= length min)
414 (sequence-type-length-mismatch-error type length)))
415 (merge-lists s1 s2 pred-fun key-fun)))
416 (sequence-type-too-hairy result-type))))
417 ((csubtypep type (specifier-type 'vector))
418 (let* ((vector-1 (coerce sequence1 'vector))
419 (vector-2 (coerce sequence2 'vector))
420 (length-1 (length vector-1))
421 (length-2 (length vector-2))
422 (result (make-sequence result-type (+ length-1 length-2))))
423 (declare (vector vector-1 vector-2)
424 (fixnum length-1 length-2))
425 (if (and (simple-vector-p result)
426 (simple-vector-p vector-1)
427 (simple-vector-p vector-2))
428 (merge-vectors vector-1 length-1 vector-2 length-2
429 result predicate key svref)
430 (merge-vectors vector-1 length-1 vector-2 length-2
431 result predicate key aref))))
432 ((and (csubtypep type (specifier-type 'sequence))
433 (awhen (find-class result-type nil)
434 (let ((predicate-function (%coerce-callable-to-fun predicate)))
435 (sb!sequence:merge
436 (sb!mop:class-prototype
437 (sb!pcl:ensure-class-finalized it))
438 sequence1 sequence2 predicate-function :key key)))))
439 (t (bad-sequence-type-error result-type)))))