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 ;;; Like CMU CL, we use HEAPSORT. However, other than that, this code
15 ;;; isn't really related to the CMU CL code, since instead of trying
16 ;;; to generalize the CMU CL code to allow START and END values, this
17 ;;; code has been written from scratch following Chapter 7 of
18 ;;; _Introduction to Algorithms_ by Corman, Rivest, and Shamir.
19 (defun sort-vector (vector start end predicate key)
20 (sort-vector vector start end predicate key))
22 ;;; This is MAYBE-INLINE because it's not too hard to have an
23 ;;; application where sorting is a major bottleneck, and inlining it
24 ;;; allows the compiler to make enough optimizations that it might be
25 ;;; worth the (large) cost in space.
26 (declaim (maybe-inline sort))
27 (defun sort (sequence predicate &key key)
29 "Destructively sort SEQUENCE. PREDICATE should return non-NIL if
30 ARG1 is to precede ARG2."
31 (let ((predicate-function (%coerce-callable-to-fun predicate))
32 (key-function (and key (%coerce-callable-to-fun key))))
34 (list (sort-list sequence predicate-function key-function))
36 (with-array-data ((vector (the vector sequence))
38 (end (length sequence)))
39 (sort-vector vector start end predicate-function key-function))
42 (error 'simple-type-error
44 :expected-type 'sequence
45 :format-control "~S is not a sequence."
46 :format-arguments (list sequence))))))
50 (defun stable-sort (sequence predicate &key key)
52 "Destructively sorts sequence. Predicate should return non-Nil if
53 Arg1 is to precede Arg2."
56 (stable-sort-simple-vector sequence predicate key))
58 (sort-list sequence predicate key))
60 (stable-sort-vector sequence predicate key))
62 (error 'simple-type-error
64 :expected-type 'sequence
65 :format-control "~S is not a sequence."
66 :format-arguments (list sequence)))))
68 ;;; stable sort of lists
70 ;;; SORT-LIST uses a bottom up merge sort. First a pass is made over
71 ;;; the list grabbing one element at a time and merging it with the
72 ;;; next one form pairs of sorted elements. Then n is doubled, and
73 ;;; elements are taken in runs of two, merging one run with the next
74 ;;; to form quadruples of sorted elements. This continues until n is
75 ;;; large enough that the inner loop only runs for one iteration; that
76 ;;; is, there are only two runs that can be merged, the first run
77 ;;; starting at the beginning of the list, and the second being the
78 ;;; remaining elements.
80 (defun sort-list (list pred key)
81 (let ((head (cons :header list)) ; head holds on to everything
82 (n 1) ; bottom-up size of lists to be merged
83 unsorted ; unsorted is the remaining list to be
84 ; broken into n size lists and merged
85 list-1 ; list-1 is one length n list to be merged
86 last) ; last points to the last visited cell
89 ;; start collecting runs of n at the first element
90 (setf unsorted (cdr head))
91 ;; tack on the first merge of two n-runs to the head holder
94 (declare (fixnum n-1))
96 (setf list-1 unsorted)
97 (let ((temp (nthcdr n-1 list-1))
100 ;; there are enough elements for a second run
101 (setf list-2 (cdr temp))
102 (setf (cdr temp) nil)
103 (setf temp (nthcdr n-1 list-2))
105 (setf unsorted (cdr temp))
106 (setf (cdr temp) nil))
107 ;; the second run goes off the end of the list
108 (t (setf unsorted nil)))
109 (multiple-value-bind (merged-head merged-last)
110 (merge-lists* list-1 list-2 pred key)
111 (setf (cdr last) merged-head)
112 (setf last merged-last))
113 (if (null unsorted) (return)))
114 ;; if there is only one run, then tack it on to the end
115 (t (setf (cdr last) list-1)
117 (setf n (ash n 1)) ; (+ n n)
118 ;; If the inner loop only executed once, then there were only
119 ;; enough elements for two runs given n, so all the elements
120 ;; have been merged into one list. This may waste one outer
121 ;; iteration to realize.
122 (if (eq list-1 (cdr head))
125 ;;; APPLY-PRED saves us a function call sometimes.
126 (eval-when (:compile-toplevel :execute)
127 (sb!xc:defmacro apply-pred (one two pred key)
129 (funcall ,pred (funcall ,key ,one)
131 (funcall ,pred ,one ,two)))
134 (defvar *merge-lists-header* (list :header))
136 ;;; MERGE-LISTS* originally written by Jim Large.
137 ;;; modified to return a pointer to the end of the result
138 ;;; and to not cons header each time its called.
139 ;;; It destructively merges list-1 with list-2. In the resulting
140 ;;; list, elements of list-2 are guaranteed to come after equal elements
142 (defun merge-lists* (list-1 list-2 pred key)
143 (let* ((result *merge-lists-header*)
144 (merge-lists-trailer (cdr *merge-lists-header*)))
146 (do ((P result)) ; points to last cell of result
147 ((or (null list-1) (null list-2)) ; done when either list used up
148 (if (null list-1) ; in which case, append the
149 (rplacd p list-2) ; other list
152 (lead (cdr p) (cdr lead)))
154 (values (cdr result) ; Return the result sans header
155 drag)))) ; and return pointer to last element.
156 (cond ((apply-pred (car list-2) (car list-1) pred key)
157 (rplacd p list-2) ; Append the lesser list to last cell of
158 (setq p (cdr p)) ; result. Note: test must be done for
159 (pop list-2)) ; LIST-2 < LIST-1 so merge will be
160 (T (rplacd p list-1) ; stable for LIST-1.
163 (setf (cdr result) merge-lists-trailer) ; (free memory, be careful)
166 ;;; stable sort of vectors
168 ;;; Stable sorting vectors is done with the same algorithm used for
169 ;;; lists, using a temporary vector to merge back and forth between it
170 ;;; and the given vector to sort.
172 (eval-when (:compile-toplevel :execute)
174 ;;; STABLE-SORT-MERGE-VECTORS* takes a source vector with subsequences,
175 ;;; start-1 (inclusive) ... end-1 (exclusive) and
176 ;;; end-1 (inclusive) ... end-2 (exclusive),
177 ;;; and merges them into a target vector starting at index start-1.
179 (sb!xc:defmacro stable-sort-merge-vectors* (source target start-1 end-1 end-2
186 (,j ,end-1) ; start-2
187 (,target-i ,start-1))
188 (declare (fixnum ,i ,j ,target-i))
191 (loop (if (= ,j ,end-2) (return))
192 (setf (,target-ref ,target ,target-i)
193 (,source-ref ,source ,j))
198 (loop (if (= ,i ,end-1) (return))
199 (setf (,target-ref ,target ,target-i)
200 (,source-ref ,source ,i))
204 ((apply-pred (,source-ref ,source ,j)
205 (,source-ref ,source ,i)
207 (setf (,target-ref ,target ,target-i)
208 (,source-ref ,source ,j))
210 (t (setf (,target-ref ,target ,target-i)
211 (,source-ref ,source ,i))
215 ;;; VECTOR-MERGE-SORT is the same algorithm used to stable sort lists,
216 ;;; but it uses a temporary vector. DIRECTION determines whether we
217 ;;; are merging into the temporary (T) or back into the given vector
219 (sb!xc:defmacro vector-merge-sort (vector pred key vector-ref)
220 (let ((vector-len (gensym)) (n (gensym))
221 (direction (gensym)) (unsorted (gensym))
222 (start-1 (gensym)) (end-1 (gensym))
223 (end-2 (gensym)) (temp-len (gensym))
225 `(let ((,vector-len (length (the vector ,vector)))
226 (,n 1) ; bottom-up size of contiguous runs to be merged
227 (,direction t) ; t vector --> temp nil temp --> vector
228 (,temp-len (length (the simple-vector *merge-sort-temp-vector*)))
229 (,unsorted 0) ; unsorted..vector-len are the elements that need
230 ; to be merged for a given n
231 (,start-1 0)) ; one n-len subsequence to be merged with the next
232 (declare (fixnum ,vector-len ,n ,temp-len ,unsorted ,start-1))
233 (if (> ,vector-len ,temp-len)
234 (setf *merge-sort-temp-vector*
235 (make-array (max ,vector-len (+ ,temp-len ,temp-len)))))
237 ;; for each n, we start taking n-runs from the start of the vector
240 (setf ,start-1 ,unsorted)
241 (let ((,end-1 (+ ,start-1 ,n)))
242 (declare (fixnum ,end-1))
243 (cond ((< ,end-1 ,vector-len)
244 ;; there are enough elements for a second run
245 (let ((,end-2 (+ ,end-1 ,n)))
246 (declare (fixnum ,end-2))
247 (if (> ,end-2 ,vector-len) (setf ,end-2 ,vector-len))
248 (setf ,unsorted ,end-2)
250 (stable-sort-merge-vectors*
251 ,vector *merge-sort-temp-vector*
252 ,start-1 ,end-1 ,end-2 ,pred ,key ,vector-ref svref)
253 (stable-sort-merge-vectors*
254 *merge-sort-temp-vector* ,vector
255 ,start-1 ,end-1 ,end-2 ,pred ,key svref ,vector-ref))
256 (if (= ,unsorted ,vector-len) (return))))
257 ;; if there is only one run, copy those elements to the end
259 (do ((,i ,start-1 (1+ ,i)))
261 (declare (fixnum ,i))
262 (setf (svref *merge-sort-temp-vector* ,i)
263 (,vector-ref ,vector ,i)))
264 (do ((,i ,start-1 (1+ ,i)))
266 (declare (fixnum ,i))
267 (setf (,vector-ref ,vector ,i)
268 (svref *merge-sort-temp-vector* ,i))))
270 ;; If the inner loop only executed once, then there were only enough
271 ;; elements for two subsequences given n, so all the elements have
272 ;; been merged into one list. Start-1 will have remained 0 upon exit.
273 (when (zerop ,start-1)
275 ;; if we just merged into the temporary, copy it all back
276 ;; to the given vector.
277 (dotimes (,i ,vector-len)
278 (setf (,vector-ref ,vector ,i)
279 (svref *merge-sort-temp-vector* ,i))))
281 (setf ,n (ash ,n 1)) ; (* 2 n)
282 (setf ,direction (not ,direction))))))
286 ;;; temporary vector for stable sorting vectors
287 (defvar *merge-sort-temp-vector*
290 (declaim (simple-vector *merge-sort-temp-vector*))
292 (defun stable-sort-simple-vector (vector pred key)
293 (declare (simple-vector vector))
294 (vector-merge-sort vector pred key svref))
296 (defun stable-sort-vector (vector pred key)
297 (vector-merge-sort vector pred key aref))
301 (eval-when (:compile-toplevel :execute)
303 ;;; MERGE-VECTORS returns a new vector which contains an interleaving
304 ;;; of the elements of VECTOR-1 and VECTOR-2. Elements from VECTOR-2
305 ;;; are chosen only if they are strictly less than elements of
306 ;;; VECTOR-1, (PRED ELT-2 ELT-1), as specified in the manual.
307 (sb!xc:defmacro merge-vectors (vector-1 length-1 vector-2 length-2
308 result-vector pred key access)
309 (let ((result-i (gensym))
312 `(let* ((,result-i 0)
315 (declare (fixnum ,result-i ,i ,j))
317 (cond ((= ,i ,length-1)
318 (loop (if (= ,j ,length-2) (return))
319 (setf (,access ,result-vector ,result-i)
320 (,access ,vector-2 ,j))
323 (return ,result-vector))
325 (loop (if (= ,i ,length-1) (return))
326 (setf (,access ,result-vector ,result-i)
327 (,access ,vector-1 ,i))
330 (return ,result-vector))
331 ((apply-pred (,access ,vector-2 ,j) (,access ,vector-1 ,i)
333 (setf (,access ,result-vector ,result-i)
334 (,access ,vector-2 ,j))
336 (t (setf (,access ,result-vector ,result-i)
337 (,access ,vector-1 ,i))
343 (defun merge (result-type sequence1 sequence2 predicate &key key)
345 "Merge the sequences SEQUENCE1 and SEQUENCE2 destructively into a
346 sequence of type RESULT-TYPE using PREDICATE to order the elements."
347 (let ((type (specifier-type result-type)))
349 ((csubtypep type (specifier-type 'list))
350 ;; the VECTOR clause, below, goes through MAKE-SEQUENCE, so
351 ;; benefits from the error checking there. Short of
352 ;; reimplementing everything, we can't do the same for the LIST
353 ;; case, so do relevant length checking here:
354 (let ((s1 (coerce sequence1 'list))
355 (s2 (coerce sequence2 'list)))
356 (when (type= type (specifier-type 'list))
357 (return-from merge (values (merge-lists* s1 s2 predicate key))))
358 (when (eq type *empty-type*)
359 (bad-sequence-type-error nil))
360 (when (type= type (specifier-type 'null))
361 (if (and (null s1) (null s2))
362 (return-from merge 'nil)
363 ;; FIXME: This will break on circular lists (as,
364 ;; indeed, will the whole MERGE function).
365 (sequence-type-length-mismatch-error type
368 (if (csubtypep (specifier-type '(cons nil t)) type)
369 (if (and (null s1) (null s2))
370 (sequence-type-length-mismatch-error type 0)
371 (values (merge-lists* s1 s2 predicate key)))
372 (sequence-type-too-hairy result-type))))
373 ((csubtypep type (specifier-type 'vector))
374 (let* ((vector-1 (coerce sequence1 'vector))
375 (vector-2 (coerce sequence2 'vector))
376 (length-1 (length vector-1))
377 (length-2 (length vector-2))
378 (result (make-sequence result-type
379 (+ length-1 length-2))))
380 (declare (vector vector-1 vector-2)
381 (fixnum length-1 length-2))
382 (if (and (simple-vector-p result)
383 (simple-vector-p vector-1)
384 (simple-vector-p vector-2))
385 (merge-vectors vector-1 length-1 vector-2 length-2
386 result predicate key svref)
387 (merge-vectors vector-1 length-1 vector-2 length-2
388 result predicate key aref))))
389 (t (bad-sequence-type-error result-type)))))