source: branches/0.17.x/abcl/src/org/armedbear/lisp/sort.lisp

Last change on this file was 11391, checked in by vvoutilainen, 17 years ago

ABCL license is GPL + Classpath exception. This was intended
by Peter Graves, the original author. For reference, see
http://sourceforge.net/mailarchive/forum.php?thread_name=20040721115302.839%40prufrock&forum_name=armedbear-j-announce

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 9.6 KB
Line 
1;;; sort.lisp
2;;;
3;;; Copyright (C) 2003-2005 Peter Graves
4;;; $Id: sort.lisp 11391 2008-11-15 22:38:34Z vvoutilainen $
5;;;
6;;; This program is free software; you can redistribute it and/or
7;;; modify it under the terms of the GNU General Public License
8;;; as published by the Free Software Foundation; either version 2
9;;; of the License, or (at your option) any later version.
10;;;
11;;; This program is distributed in the hope that it will be useful,
12;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14;;; GNU General Public License for more details.
15;;;
16;;; You should have received a copy of the GNU General Public License
17;;; along with this program; if not, write to the Free Software
18;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19;;;
20;;; As a special exception, the copyright holders of this library give you
21;;; permission to link this library with independent modules to produce an
22;;; executable, regardless of the license terms of these independent
23;;; modules, and to copy and distribute the resulting executable under
24;;; terms of your choice, provided that you also meet, for each linked
25;;; independent module, the terms and conditions of the license of that
26;;; module.  An independent module is a module which is not derived from
27;;; or based on this library.  If you modify this library, you may extend
28;;; this exception to your version of the library, but you are not
29;;; obligated to do so.  If you do not wish to do so, delete this
30;;; exception statement from your version.
31
32(in-package #:system)
33
34(defun sort (sequence predicate &key key)
35  (if (listp sequence)
36      (sort-list sequence predicate key)
37      (quick-sort sequence 0 (length sequence) predicate key)))
38
39(defun stable-sort (sequence predicate &key key)
40  (if (listp sequence)
41      (sort-list sequence predicate key)
42      (quick-sort sequence 0 (length sequence) predicate key)))
43
44;; Adapted from SBCL.
45(declaim (ftype (function (list) cons) last-cons-of))
46(defun last-cons-of (list)
47  (loop
48    (let ((rest (rest list)))
49      (if rest
50          (setf list rest)
51          (return list)))))
52
53;; Adapted from OpenMCL.
54(defun merge-lists (list1 list2 pred key)
55  (declare (optimize (speed 3) (safety 0)))
56  (if (null key)
57      (merge-lists-no-key list1 list2 pred)
58      (cond ((null list1)
59             (values list2 (last-cons-of list2)))
60            ((null list2)
61             (values list1 (last-cons-of list1)))
62            (t
63             (let* ((result (cons nil nil))
64                    (p result)               ; p points to last cell of result
65                    (key1 (funcall key (car list1)))
66                    (key2 (funcall key (car list2))))
67               (declare (type list p))
68               (loop
69                 (cond ((funcall pred key2 key1)
70                        (rplacd p list2)     ; append the lesser list to last cell of
71                        (setf p (cdr p))     ;   result.  Note: test must bo done for
72                        (pop list2)          ;   list2 < list1 so merge will be
73                        (unless list2        ;   stable for list1
74                          (rplacd p list1)
75                          (return (values (cdr result) (last-cons-of p))))
76                        (setf key2 (funcall key (car list2))))
77                       (t
78                        (rplacd p list1)
79                        (setf p (cdr p))
80                        (pop list1)
81                        (unless list1
82                          (rplacd p list2)
83                          (return (values (cdr result) (last-cons-of p))))
84                        (setf key1 (funcall key (car list1)))))))))))
85
86(defun merge-lists-no-key (list1 list2 pred)
87  (declare (optimize (speed 3) (safety 0)))
88  (cond ((null list1)
89         (values list2 (last-cons-of list2)))
90        ((null list2)
91         (values list1 (last-cons-of list1)))
92        (t
93         (let* ((result (cons nil nil))
94                (p result)                   ; p points to last cell of result
95                (key1 (car list1))
96                (key2 (car list2)))
97           (declare (type list p))
98           (loop
99             (cond ((funcall pred key2 key1)
100                    (rplacd p list2)         ; append the lesser list to last cell of
101                    (setf p (cdr p))         ;   result.  Note: test must bo done for
102                    (pop list2)              ;   list2 < list1 so merge will be
103                    (unless list2            ;   stable for list1
104                      (rplacd p list1)
105                      (return (values (cdr result) (last-cons-of p))))
106                    (setf key2 (car list2)))
107                   (t
108                    (rplacd p list1)
109                    (setf p (cdr p))
110                    (pop list1)
111                    (unless list1
112                      (rplacd p list2)
113                      (return (values (cdr result) (last-cons-of p))))
114                    (setf key1 (car list1)))))))))
115
116;;; SORT-LIST uses a bottom up merge sort.  First a pass is made over
117;;; the list grabbing one element at a time and merging it with the next one
118;;; form pairs of sorted elements.  Then n is doubled, and elements are taken
119;;; in runs of two, merging one run with the next to form quadruples of sorted
120;;; elements.  This continues until n is large enough that the inner loop only
121;;; runs for one iteration; that is, there are only two runs that can be merged,
122;;; the first run starting at the beginning of the list, and the second being
123;;; the remaining elements.
124
125(defun sort-list (list pred key)
126  (when (or (eq key #'identity) (eq key 'identity))
127    (setf key nil))
128  (let ((head (cons nil list)) ; head holds on to everything
129        (n 1)                  ; bottom-up size of lists to be merged
130        unsorted               ; unsorted is the remaining list to be
131                               ;   broken into n size lists and merged
132        list-1                 ; list-1 is one length n list to be merged
133        last                   ; last points to the last visited cell
134        )
135    (declare (type fixnum n))
136    (loop
137      ;; start collecting runs of n at the first element
138      (setf unsorted (cdr head))
139      ;; tack on the first merge of two n-runs to the head holder
140      (setf last head)
141      (let ((n-1 (1- n)))
142        (declare (type fixnum n-1))
143        (loop
144          (setf list-1 unsorted)
145          (let ((temp (nthcdr n-1 list-1))
146                list-2)
147            (cond (temp
148                   ;; there are enough elements for a second run
149                   (setf list-2 (cdr temp))
150                   (setf (cdr temp) nil)
151                   (setf temp (nthcdr n-1 list-2))
152                   (cond (temp
153                          (setf unsorted (cdr temp))
154                          (setf (cdr temp) nil))
155                         ;; the second run goes off the end of the list
156                         (t (setf unsorted nil)))
157                   (multiple-value-bind (merged-head merged-last)
158                       (merge-lists list-1 list-2 pred key)
159                     (setf (cdr last) merged-head)
160                     (setf last merged-last))
161                   (if (null unsorted) (return)))
162                  ;; if there is only one run, then tack it on to the end
163                  (t (setf (cdr last) list-1)
164                     (return)))))
165        (setf n (+ n n))
166        ;; If the inner loop only executed once, then there were only enough
167        ;; elements for two runs given n, so all the elements have been merged
168        ;; into one list.  This may waste one outer iteration to realize.
169        (if (eq list-1 (cdr head))
170            (return list-1))))))
171
172;;; From ECL.
173(defun quick-sort (seq start end pred key)
174  (unless key (setq key #'identity))
175  (if (<= end (1+ start))
176      seq
177      (let* ((j start) (k end) (d (elt seq start)) (kd (funcall key d)))
178        (block outer-loop
179          (loop (loop (decf k)
180                  (unless (< j k) (return-from outer-loop))
181                  (when (funcall pred (funcall key (elt seq k)) kd)
182                    (return)))
183            (loop (incf j)
184              (unless (< j k) (return-from outer-loop))
185              (unless (funcall pred (funcall key (elt seq j)) kd)
186                (return)))
187            (let ((temp (elt seq j)))
188              (setf (elt seq j) (elt seq k)
189                    (elt seq k) temp))))
190        (setf (elt seq start) (elt seq j)
191              (elt seq j) d)
192        (quick-sort seq start j pred key)
193        (quick-sort seq (1+ j) end pred key))))
194
195;;; From ECL.
196(defun merge (result-type sequence1 sequence2 predicate
197                          &key key
198                          &aux (l1 (length sequence1)) (l2 (length sequence2)))
199  (unless key (setq key #'identity))
200  (do ((newseq (make-sequence result-type (+ l1 l2)))
201       (j 0 (1+ j))
202       (i1 0)
203       (i2 0))
204    ((and (= i1 l1) (= i2 l2)) newseq)
205    (cond ((and (< i1 l1) (< i2 l2))
206           (cond ((funcall predicate
207                           (funcall key (elt sequence1 i1))
208                           (funcall key (elt sequence2 i2)))
209                  (setf (elt newseq j) (elt sequence1 i1))
210                  (incf i1))
211                 ((funcall predicate
212                           (funcall key (elt sequence2 i2))
213                           (funcall key (elt sequence1 i1)))
214                  (setf (elt newseq j) (elt sequence2 i2))
215                  (incf i2))
216                 (t
217                  (setf (elt newseq j) (elt sequence1 i1))
218                  (incf i1))))
219          ((< i1 l1)
220           (setf (elt newseq j) (elt sequence1 i1))
221           (incf i1))
222          (t
223           (setf (elt newseq j) (elt sequence2 i2))
224           (incf i2)))))
Note: See TracBrowser for help on using the repository browser.