1.0.36.18: remove *MERGE-SORT-TEMP-VECTOR* and *ZAP-ARRAY-DATA-TEMP*
[sbcl.git] / src / code / sort.lisp
1 ;;;; SORT and friends
2
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.
11
12 (in-package "SB!IMPL")
13
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))
16
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))
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))))
40 \f
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))))
60 \f
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
69 \f
70 ;;;; stable sort of lists
71
72 (defun last-cons-of (list)
73   (loop (let ((rest (rest list)))
74           (if rest
75               (setf list rest)
76               (return list)))))
77
78 ;;; Destructively merge LIST-1 with LIST-2 (given that they're already
79 ;;; sorted w.r.t. PRED-FUN on KEY-FUN, giving output sorted the same
80 ;;; way). In the resulting list, elements of LIST-1 are guaranteed to
81 ;;; come before equal elements of LIST-2.
82 ;;;
83 ;;; Return (VALUES HEAD TAILTAIL), where HEAD is the same value you'd
84 ;;; expect from MERGE, and TAILTAIL is the last cons in the list (i.e.
85 ;;; the last cons in the list which NRECONC calls TAIL).
86 (defun merge-lists* (list-1 list-2 pred-fun key-fun)
87   (declare (type list list-1 list-2))
88   (declare (type function pred-fun key-fun))
89   (cond ((null list-1) (values list-2 (last-cons-of list-2)))
90         ((null list-2) (values list-1 (last-cons-of list-1)))
91         (t (let* ((reversed-result-so-far nil)
92                   (key-1 (funcall key-fun (car list-1)))
93                   (key-2 (funcall key-fun (car list-2))))
94              (loop
95               (macrolet ((frob (list-i key-i other-list)
96                            `(progn
97                               ;; basically
98                               ;;   (PUSH (POP ,LIST-I) REVERSED-RESULT-SO-FAR),
99                               ;; except doing some fancy footwork to
100                               ;; reuse the cons cell:
101                               (psetf (cdr ,list-i) reversed-result-so-far
102                                      reversed-result-so-far ,list-i
103                                      ,list-i (cdr ,list-i))
104                               ;; Now maybe we're done.
105                               (if (endp ,list-i)
106                                   (return (values (nreconc
107                                                    reversed-result-so-far
108                                                    ,other-list)
109                                                   (last-cons-of
110                                                    ,other-list)))
111                                   (setf ,key-i
112                                         (funcall key-fun (car ,list-i)))))))
113                 ;; Note that by making KEY-2 the first arg to
114                 ;; PRED-FUN, we arrange that if PRED-FUN is a function
115                 ;; in the #'< style, the outcome is stably sorted.
116                 (if (funcall pred-fun key-2 key-1)
117                     (frob list-2 key-2 list-1)
118                     (frob list-1 key-1 list-2))))))))
119
120 ;;; STABLE-SORT-LIST uses a bottom-up merge sort. First a pass is made
121 ;;; over the list grabbing one element at a time and merging it with
122 ;;; the next one to form pairs of sorted elements. Then N is doubled,
123 ;;; and elements are taken in runs of two, merging one run with the
124 ;;; next to form quadruples of sorted elements. This continues until N
125 ;;; is large enough that the inner loop only runs for one iteration;
126 ;;; that is, there are only two runs that can be merged, the first run
127 ;;; starting at the beginning of the list, and the second being the
128 ;;; remaining elements.
129 (defun stable-sort-list (list pred-fun key-fun)
130   (let ((head (cons :header list))  ; head holds on to everything
131         (n 1)                       ; bottom-up size of lists to be merged
132         unsorted                    ; unsorted is the remaining list to be
133                                     ;   broken into n size lists and merged
134         list-1                      ; list-1 is one length n list to be merged
135         last)                       ; last points to the last visited cell
136     (declare (type function pred-fun key-fun)
137              (type fixnum n))
138     (loop
139      ;; Start collecting runs of N at the first element.
140      (setf unsorted (cdr head))
141      ;; Tack on the first merge of two N-runs to the head holder.
142      (setf last head)
143      (let ((n-1 (1- n)))
144        (declare (fixnum n-1))
145        (loop
146         (setf list-1 unsorted)
147         (let ((temp (nthcdr n-1 list-1))
148               list-2)
149           (cond (temp
150                  ;; There are enough elements for a second run.
151                  (setf list-2 (cdr temp))
152                  (setf (cdr temp) nil)
153                  (setf temp (nthcdr n-1 list-2))
154                  (cond (temp
155                         (setf unsorted (cdr temp))
156                         (setf (cdr temp) nil))
157                        ;; The second run goes off the end of the list.
158                        (t (setf unsorted nil)))
159                  (multiple-value-bind (merged-head merged-last)
160                      (merge-lists* list-1 list-2 pred-fun key-fun)
161                    (setf (cdr last) merged-head
162                          last merged-last))
163                  (if (null unsorted) (return)))
164                 ;; If there is only one run, then tack it on to the end.
165                 (t (setf (cdr last) list-1)
166                    (return)))))
167        (setf n (ash n 1)) ; (+ n n)
168        ;; If the inner loop only executed once, then there were only
169        ;; enough elements for two runs given n, so all the elements
170        ;; have been merged into one list. This may waste one outer
171        ;; iteration to realize.
172        (if (eq list-1 (cdr head))
173            (return list-1))))))
174 \f
175 ;;;; stable sort of vectors
176
177 ;;; Stable sorting vectors is done with the same algorithm used for
178 ;;; lists, using a temporary vector to merge back and forth between it
179 ;;; and the given vector to sort.
180
181 (eval-when (:compile-toplevel :execute)
182
183 ;;; STABLE-SORT-MERGE-VECTORS* takes a source vector with subsequences,
184 ;;;    start-1 (inclusive) ... end-1 (exclusive) and
185 ;;;    end-1 (inclusive) ... end-2 (exclusive),
186 ;;; and merges them into a target vector starting at index start-1.
187
188 (sb!xc:defmacro stable-sort-merge-vectors* (source target start-1 end-1 end-2
189                                                      pred key source-ref
190                                                      target-ref)
191   (let ((i (gensym))
192         (j (gensym))
193         (target-i (gensym)))
194     `(let ((,i ,start-1)
195            (,j ,end-1) ; start-2
196            (,target-i ,start-1))
197        (declare (fixnum ,i ,j ,target-i))
198        (loop
199         (cond ((= ,i ,end-1)
200                (loop (if (= ,j ,end-2) (return))
201                      (setf (,target-ref ,target ,target-i)
202                            (,source-ref ,source ,j))
203                      (incf ,target-i)
204                      (incf ,j))
205                (return))
206               ((= ,j ,end-2)
207                (loop (if (= ,i ,end-1) (return))
208                      (setf (,target-ref ,target ,target-i)
209                            (,source-ref ,source ,i))
210                      (incf ,target-i)
211                      (incf ,i))
212                (return))
213               ((funcall2-using-key ,pred ,key
214                                    (,source-ref ,source ,j)
215                                    (,source-ref ,source ,i))
216                (setf (,target-ref ,target ,target-i)
217                      (,source-ref ,source ,j))
218                (incf ,j))
219               (t (setf (,target-ref ,target ,target-i)
220                        (,source-ref ,source ,i))
221                  (incf ,i)))
222         (incf ,target-i)))))
223
224 ;;; VECTOR-MERGE-SORT is the same algorithm used to stable sort lists,
225 ;;; but it uses a temporary vector. DIRECTION determines whether we
226 ;;; are merging into the temporary (T) or back into the given vector
227 ;;; (NIL).
228 (sb!xc:defmacro vector-merge-sort (vector pred key vector-ref)
229   (with-unique-names
230       (vector-len n direction unsorted start-1 end-1 end-2 temp i)
231     `(let* ((,vector-len (length (the vector ,vector)))
232             (,n 1)            ; bottom-up size of contiguous runs to be merged
233             (,direction t)    ; t vector --> temp    nil temp --> vector
234             (,temp (make-array ,vector-len))
235             (,unsorted 0)   ; unsorted..vector-len are the elements that need
236                                         ; to be merged for a given n
237             (,start-1 0))   ; one n-len subsequence to be merged with the next
238        (declare (fixnum ,vector-len ,n ,unsorted ,start-1)
239                 (simple-vector ,temp))
240        (loop
241          ;; for each n, we start taking n-runs from the start of the vector
242          (setf ,unsorted 0)
243          (loop
244            (setf ,start-1 ,unsorted)
245            (let ((,end-1 (+ ,start-1 ,n)))
246              (declare (fixnum ,end-1))
247              (cond ((< ,end-1 ,vector-len)
248                     ;; there are enough elements for a second run
249                     (let ((,end-2 (+ ,end-1 ,n)))
250                       (declare (fixnum ,end-2))
251                       (if (> ,end-2 ,vector-len) (setf ,end-2 ,vector-len))
252                       (setf ,unsorted ,end-2)
253                       (if ,direction
254                           (stable-sort-merge-vectors*
255                            ,vector ,temp
256                            ,start-1 ,end-1 ,end-2 ,pred ,key ,vector-ref svref)
257                           (stable-sort-merge-vectors*
258                            ,temp ,vector
259                            ,start-1 ,end-1 ,end-2 ,pred ,key svref ,vector-ref))
260                       (if (= ,unsorted ,vector-len) (return))))
261                    ;; if there is only one run, copy those elements to the end
262                    (t (if ,direction
263                           (do ((,i ,start-1 (1+ ,i)))
264                               ((= ,i ,vector-len))
265                             (declare (fixnum ,i))
266                             (setf (svref ,temp ,i) (,vector-ref ,vector ,i)))
267                           (do ((,i ,start-1 (1+ ,i)))
268                               ((= ,i ,vector-len))
269                             (declare (fixnum ,i))
270                             (setf (,vector-ref ,vector ,i) (svref ,temp ,i))))
271                       (return)))))
272          ;; If the inner loop only executed once, then there were only enough
273          ;; elements for two subsequences given n, so all the elements have
274          ;; been merged into one list. Start-1 will have remained 0 upon exit.
275          (when (zerop ,start-1)
276            (when ,direction
277              ;; if we just merged into the temporary, copy it all back
278              ;; to the given vector.
279              (dotimes (,i ,vector-len)
280                (setf (,vector-ref ,vector ,i) (svref ,temp ,i))))
281            ;; Kill the new vector to prevent garbage from being retained.
282            (%shrink-vector ,temp 0)
283            (return ,vector))
284          (setf ,n (ash ,n 1))           ; (* 2 n)
285          (setf ,direction (not ,direction))))))
286
287 ) ; EVAL-when
288
289 (defun stable-sort-simple-vector (vector pred key)
290   (declare (type simple-vector vector)
291            (type function pred)
292            (type (or null function) key))
293   (vector-merge-sort vector pred key svref))
294
295 (defun stable-sort-vector (vector pred key)
296   (declare (type function pred)
297            (type (or null function) key))
298   (vector-merge-sort vector pred key aref))
299 \f
300 ;;;; merging
301
302 (eval-when (:compile-toplevel :execute)
303
304 ;;; MERGE-VECTORS returns a new vector which contains an interleaving
305 ;;; of the elements of VECTOR-1 and VECTOR-2. Elements from VECTOR-2
306 ;;; are chosen only if they are strictly less than elements of
307 ;;; VECTOR-1, (PRED ELT-2 ELT-1), as specified in the manual.
308 (sb!xc:defmacro merge-vectors (vector-1 length-1 vector-2 length-2
309                                result-vector pred key access)
310   (let ((result-i (gensym))
311         (i (gensym))
312         (j (gensym)))
313     `(let* ((,result-i 0)
314             (,i 0)
315             (,j 0))
316        (declare (fixnum ,result-i ,i ,j))
317        (loop
318         (cond ((= ,i ,length-1)
319                (loop (if (= ,j ,length-2) (return))
320                      (setf (,access ,result-vector ,result-i)
321                            (,access ,vector-2 ,j))
322                      (incf ,result-i)
323                      (incf ,j))
324                (return ,result-vector))
325               ((= ,j ,length-2)
326                (loop (if (= ,i ,length-1) (return))
327                      (setf (,access ,result-vector ,result-i)
328                            (,access ,vector-1 ,i))
329                      (incf ,result-i)
330                      (incf ,i))
331                (return ,result-vector))
332               ((funcall2-using-key ,pred ,key
333                                    (,access ,vector-2 ,j) (,access ,vector-1 ,i))
334                (setf (,access ,result-vector ,result-i)
335                      (,access ,vector-2 ,j))
336                (incf ,j))
337               (t (setf (,access ,result-vector ,result-i)
338                        (,access ,vector-1 ,i))
339                  (incf ,i)))
340         (incf ,result-i)))))
341
342 ) ; EVAL-WHEN
343
344 (defun merge (result-type sequence1 sequence2 predicate &key key)
345   #!+sb-doc
346   "Merge the sequences SEQUENCE1 and SEQUENCE2 destructively into a
347    sequence of type RESULT-TYPE using PREDICATE to order the elements."
348   ;; FIXME: This implementation is remarkably inefficient in various
349   ;; ways. In decreasing order of estimated user astonishment, I note:
350   ;; full calls to SPECIFIER-TYPE at runtime; copying input vectors
351   ;; to lists before doing MERGE-LISTS*; and walking input lists
352   ;; (because of the call to MERGE-LISTS*, which walks the list to
353   ;; find the last element for its second return value) even in cases
354   ;; like (MERGE 'LIST (LIST 1) (LIST 2 3 4 5 ... 1000)) where one list
355   ;; can be largely ignored. -- WHN 2003-01-05
356   (let ((type (specifier-type result-type)))
357     (cond
358       ((csubtypep type (specifier-type 'list))
359        ;; the VECTOR clause, below, goes through MAKE-SEQUENCE, so
360        ;; benefits from the error checking there. Short of
361        ;; reimplementing everything, we can't do the same for the LIST
362        ;; case, so do relevant length checking here:
363        (let ((s1 (coerce sequence1 'list))
364              (s2 (coerce sequence2 'list))
365              (pred-fun (%coerce-callable-to-fun predicate))
366              (key-fun (if key
367                           (%coerce-callable-to-fun key)
368                           #'identity)))
369          (when (type= type (specifier-type 'list))
370            (return-from merge (values (merge-lists* s1 s2 pred-fun key-fun))))
371          (when (eq type *empty-type*)
372            (bad-sequence-type-error nil))
373          (when (type= type (specifier-type 'null))
374            (if (and (null s1) (null s2))
375                (return-from merge 'nil)
376                ;; FIXME: This will break on circular lists (as,
377                ;; indeed, will the whole MERGE function).
378                (sequence-type-length-mismatch-error type
379                                                     (+ (length s1)
380                                                        (length s2)))))
381          (if (cons-type-p type)
382              (multiple-value-bind (min exactp)
383                  (sb!kernel::cons-type-length-info type)
384                (let ((length (+ (length s1) (length s2))))
385                  (if exactp
386                      (unless (= length min)
387                        (sequence-type-length-mismatch-error type length))
388                      (unless (>= length min)
389                        (sequence-type-length-mismatch-error type length)))
390                  (values (merge-lists* s1 s2 pred-fun key-fun))))
391              (sequence-type-too-hairy result-type))))
392       ((csubtypep type (specifier-type 'vector))
393        (let* ((vector-1 (coerce sequence1 'vector))
394               (vector-2 (coerce sequence2 'vector))
395               (length-1 (length vector-1))
396               (length-2 (length vector-2))
397               (result (make-sequence result-type (+ length-1 length-2))))
398          (declare (vector vector-1 vector-2)
399                   (fixnum length-1 length-2))
400          (if (and (simple-vector-p result)
401                   (simple-vector-p vector-1)
402                   (simple-vector-p vector-2))
403              (merge-vectors vector-1 length-1 vector-2 length-2
404                             result predicate key svref)
405              (merge-vectors vector-1 length-1 vector-2 length-2
406                             result predicate key aref))))
407       ((and (csubtypep type (specifier-type 'sequence))
408             (find-class result-type nil))
409        (let* ((vector-1 (coerce sequence1 'vector))
410               (vector-2 (coerce sequence2 'vector))
411               (length-1 (length vector-1))
412               (length-2 (length vector-2))
413               (temp (make-array (+ length-1 length-2)))
414               (result (make-sequence result-type (+ length-1 length-2))))
415          (declare (vector vector-1 vector-2) (fixnum length-1 length-2))
416          (merge-vectors vector-1 length-1 vector-2 length-2
417                         temp predicate key aref)
418          (replace result temp)
419          result))
420       (t (bad-sequence-type-error result-type)))))