| 1 | ;;; list merge & list merge-sort -*- Scheme -*- |
| 2 | ;;; Copyright (c) 1998 by Olin Shivers. |
| 3 | ;;; This code is open-source; see the end of the file for porting and |
| 4 | ;;; more copyright information. |
| 5 | ;;; Olin Shivers |
| 6 | |
| 7 | ;;; Exports: |
| 8 | ;;; (list-merge < lis lis) -> list |
| 9 | ;;; (list-merge! < lis lis) -> list |
| 10 | ;;; (list-merge-sort < lis) -> list |
| 11 | ;;; (list-merge-sort! < lis) -> list |
| 12 | |
| 13 | ;;; A stable list merge sort of my own device |
| 14 | ;;; Two variants: pure & destructive |
| 15 | ;;; |
| 16 | ;;; This list merge sort is opportunistic (a "natural" sort) -- it exploits |
| 17 | ;;; existing order in the input set. Instead of recursing all the way down to |
| 18 | ;;; individual elements, the leaves of the merge tree are maximal contiguous |
| 19 | ;;; runs of elements from the input list. So the algorithm does very well on |
| 20 | ;;; data that is mostly ordered, with a best-case time of O(n) when the input |
| 21 | ;;; list is already completely sorted. In any event, worst-case time is |
| 22 | ;;; O(n lg n). |
| 23 | ;;; |
| 24 | ;;; The destructive variant is "in place," meaning that it allocates no new |
| 25 | ;;; cons cells at all; it just rearranges the pairs of the input list with |
| 26 | ;;; SET-CDR! to order it. |
| 27 | ;;; |
| 28 | ;;; The interesting control structure is the combination recursion/iteration |
| 29 | ;;; of the core GROW function that does an "opportunistic" DFS walk of the |
| 30 | ;;; merge tree, adaptively subdividing in response to the length of the |
| 31 | ;;; merges, without requiring any auxiliary data structures beyond the |
| 32 | ;;; recursion stack. It's actually quite simple -- ten lines of code. |
| 33 | ;;; -Olin Shivers 10/20/98 |
| 34 | |
| 35 | ;;; (mlet ((var-list mv-exp) ...) body ...) |
| 36 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
| 37 | ;;; A LET* form that handles multiple values. Move this into the two clients |
| 38 | ;;; if you don't have a module system handy to restrict its visibility... |
| 39 | (define-syntax mlet ; Multiple-value LET* |
| 40 | (syntax-rules () |
| 41 | ((mlet ((() exp) rest ...) body ...) |
| 42 | (begin exp (mlet (rest ...) body ...))) |
| 43 | |
| 44 | ((mlet (((var) exp) rest ...) body ...) |
| 45 | (let ((var exp)) (mlet (rest ...) body ...))) |
| 46 | |
| 47 | ((mlet ((vars exp) rest ...) body ...) |
| 48 | (call-with-values (lambda () exp) |
| 49 | (lambda vars (mlet (rest ...) body ...)))) |
| 50 | |
| 51 | ((mlet () body ...) (begin body ...)))) |
| 52 | |
| 53 | |
| 54 | ;;; (list-merge-sort < lis) |
| 55 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
| 56 | ;;; A natural, stable list merge sort. |
| 57 | ;;; - natural: picks off maximal contiguous runs of pre-ordered data. |
| 58 | ;;; - stable: won't invert the order of equal elements in the input list. |
| 59 | |
| 60 | (define (list-merge-sort elt< lis) |
| 61 | |
| 62 | ;; (getrun lis) -> run runlen rest |
| 63 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
| 64 | ;; Pick a run of non-decreasing data off of non-empty list LIS. |
| 65 | ;; Return the length of this run, and the following list. |
| 66 | (define (getrun lis) |
| 67 | (let lp ((ans '()) (i 1) (prev (car lis)) (xs (cdr lis))) |
| 68 | (if (pair? xs) |
| 69 | (let ((x (car xs))) |
| 70 | (if (elt< x prev) |
| 71 | (values (append-reverse ans (cons prev '())) i xs) |
| 72 | (lp (cons prev ans) (+ i 1) x (cdr xs)))) |
| 73 | (values (append-reverse ans (cons prev '())) i xs)))) |
| 74 | |
| 75 | (define (append-reverse rev-head tail) |
| 76 | (let lp ((rev-head rev-head) (tail tail)) |
| 77 | (if (null-list? rev-head) tail |
| 78 | (lp (cdr rev-head) (cons (car rev-head) tail))))) |
| 79 | |
| 80 | (define (null-list? l) |
| 81 | (cond ((pair? l) #f) |
| 82 | ((null? l) #t) |
| 83 | (else (error "argument out of domain" l)))) |
| 84 | |
| 85 | ;; (merge a b) -> list |
| 86 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
| 87 | ;; List merge -- stably merge lists A (length > 0) & B (length > 0). |
| 88 | ;; This version requires up to |a|+|b| stack frames. |
| 89 | (define (merge a b) |
| 90 | (let recur ((x (car a)) (a a) |
| 91 | (y (car b)) (b b)) |
| 92 | (if (elt< y x) |
| 93 | (cons y (let ((b (cdr b))) |
| 94 | (if (pair? b) |
| 95 | (recur x a (car b) b) |
| 96 | a))) |
| 97 | (cons x (let ((a (cdr a))) |
| 98 | (if (pair? a) |
| 99 | (recur (car a) a y b) |
| 100 | b)))))) |
| 101 | |
| 102 | ;; (grow s ls ls2 u lw) -> [a la unused] |
| 103 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
| 104 | ;; The core routine. Read the next 20 lines of comments & all is obvious. |
| 105 | ;; - S is a sorted list of length LS > 1. |
| 106 | ;; - LS2 is some power of two <= LS. |
| 107 | ;; - U is an unsorted list. |
| 108 | ;; - LW is a positive integer. |
| 109 | ;; Starting with S, and taking data from U as needed, produce |
| 110 | ;; a sorted list of *at least* length LW, if there's enough data |
| 111 | ;; (LW <= LS + length(U)), or use all of U if not. |
| 112 | ;; |
| 113 | ;; GROW takes maximal contiguous runs of data from U at a time; |
| 114 | ;; it is allowed to return a list *longer* than LW if it gets lucky |
| 115 | ;; with a long run. |
| 116 | ;; |
| 117 | ;; The key idea: If you want a merge operation to "pay for itself," the two |
| 118 | ;; lists being merged should be about the same length. Remember that. |
| 119 | ;; |
| 120 | ;; Returns: |
| 121 | ;; - A: The result list |
| 122 | ;; - LA: The length of the result list |
| 123 | ;; - UNUSED: The unused tail of U. |
| 124 | |
| 125 | (define (grow s ls ls2 u lw) ; The core of the sort algorithm. |
| 126 | (if (or (<= lw ls) (not (pair? u))) ; Met quota or out of data? |
| 127 | (values s ls u) ; If so, we're done. |
| 128 | (mlet (((ls2) (let lp ((ls2 ls2)) |
| 129 | (let ((ls2*2 (+ ls2 ls2))) |
| 130 | (if (<= ls2*2 ls) (lp ls2*2) ls2)))) |
| 131 | ;; LS2 is now the largest power of two <= LS. |
| 132 | ;; (Just think of it as being roughly LS.) |
| 133 | ((r lr u2) (getrun u)) ; Get a run, then |
| 134 | ((t lt u3) (grow r lr 1 u2 ls2))) ; grow it up to be T. |
| 135 | (grow (merge s t) (+ ls lt) ; Merge S & T, |
| 136 | (+ ls2 ls2) u3 lw)))) ; and loop. |
| 137 | |
| 138 | ;; Note: (LENGTH LIS) or any constant guaranteed |
| 139 | ;; to be greater can be used in place of INFINITY. |
| 140 | (if (pair? lis) ; Don't sort an empty list. |
| 141 | (mlet (((r lr tail) (getrun lis)) ; Pick off an initial run, |
| 142 | ((infinity) #o100000000) ; then grow it up maximally. |
| 143 | ((a la v) (grow r lr 1 tail infinity))) |
| 144 | a) |
| 145 | '())) |
| 146 | |
| 147 | |
| 148 | ;;; (list-merge-sort! < lis) |
| 149 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
| 150 | ;;; A natural, stable, destructive, in-place list merge sort. |
| 151 | ;;; - natural: picks off maximal contiguous runs of pre-ordered data. |
| 152 | ;;; - stable: won't invert the order of equal elements in the input list. |
| 153 | ;;; - destructive, in-place: this routine allocates no extra working memory; |
| 154 | ;;; it simply rearranges the list with SET-CDR! operations. |
| 155 | |
| 156 | (define (list-merge-sort! elt< lis) |
| 157 | ;; (getrun lis) -> runlen last rest |
| 158 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
| 159 | ;; Pick a run of non-decreasing data off of non-empty list LIS. |
| 160 | ;; Return the length of this run, the last cons cell of the run, |
| 161 | ;; and the following list. |
| 162 | (define (getrun lis) |
| 163 | (let lp ((lis lis) (x (car lis)) (i 1) (next (cdr lis))) |
| 164 | (if (pair? next) |
| 165 | (let ((y (car next))) |
| 166 | (if (elt< y x) |
| 167 | (values i lis next) |
| 168 | (lp next y (+ i 1) (cdr next)))) |
| 169 | (values i lis next)))) |
| 170 | |
| 171 | ;; (merge! a enda b endb) -> [m endm] |
| 172 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
| 173 | ;; Destructively and stably merge non-empty lists A & B. |
| 174 | ;; The last cons of A is ENDA. (The cdr of ENDA can be non-nil.) |
| 175 | ;; the last cons of B is ENDB. (The cdr of ENDB can be non-nil.) |
| 176 | ;; |
| 177 | ;; Return the first and last cons cells of the merged list. |
| 178 | ;; This routine is iterative & in-place: it runs in constant stack and |
| 179 | ;; doesn't allocate any cons cells. It is also tedious but simple; don't |
| 180 | ;; bother reading it unless necessary. |
| 181 | (define (merge! a enda b endb) |
| 182 | ;; The logic of these two loops is completely driven by these invariants: |
| 183 | ;; SCAN-A: (CDR PREV) = A. X = (CAR A). Y = (CAR B). |
| 184 | ;; SCAN-B: (CDR PREV) = B. X = (CAR A). Y = (CAR B). |
| 185 | (letrec ((scan-a (lambda (prev x a y b) ; Zip down A until we |
| 186 | (cond ((elt< y x) ; find an elt > (CAR B). |
| 187 | (set-cdr! prev b) |
| 188 | (let ((next-b (cdr b))) |
| 189 | (if (eq? b endb) |
| 190 | (begin (set-cdr! b a) enda) ; Done. |
| 191 | (scan-b b x a (car next-b) next-b)))) |
| 192 | |
| 193 | ((eq? a enda) (maybe-set-cdr! a b) endb) ; Done. |
| 194 | |
| 195 | (else (let ((next-a (cdr a))) ; Continue scan. |
| 196 | (scan-a a (car next-a) next-a y b)))))) |
| 197 | |
| 198 | (scan-b (lambda (prev x a y b) ; Zip down B while its |
| 199 | (cond ((elt< y x) ; elts are < (CAR A). |
| 200 | (if (eq? b endb) |
| 201 | (begin (set-cdr! b a) enda) ; Done. |
| 202 | (let ((next-b (cdr b))) ; Continue scan. |
| 203 | (scan-b b x a (car next-b) next-b)))) |
| 204 | |
| 205 | (else (set-cdr! prev a) |
| 206 | (if (eq? a enda) |
| 207 | (begin (maybe-set-cdr! a b) endb) ; Done. |
| 208 | (let ((next-a (cdr a))) |
| 209 | (scan-a a (car next-a) next-a y b))))))) |
| 210 | |
| 211 | ;; This guy only writes if he has to. Called at most once. |
| 212 | ;; Pointer equality rules; pure languages are for momma's boys. |
| 213 | (maybe-set-cdr! (lambda (pair val) (if (not (eq? (cdr pair) val)) |
| 214 | (set-cdr! pair val))))) |
| 215 | |
| 216 | (let ((x (car a)) (y (car b))) |
| 217 | (if (elt< y x) |
| 218 | |
| 219 | ;; B starts the answer list. |
| 220 | (values b (if (eq? b endb) |
| 221 | (begin (set-cdr! b a) enda) |
| 222 | (let ((next-b (cdr b))) |
| 223 | (scan-b b x a (car next-b) next-b)))) |
| 224 | |
| 225 | ;; A starts the answer list. |
| 226 | (values a (if (eq? a enda) |
| 227 | (begin (maybe-set-cdr! a b) endb) |
| 228 | (let ((next-a (cdr a))) |
| 229 | (scan-a a (car next-a) next-a y b)))))))) |
| 230 | |
| 231 | ;; (grow s ends ls ls2 u lw) -> [a enda la unused] |
| 232 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
| 233 | ;; The core routine. |
| 234 | ;; - S is a sorted list of length LS > 1, with final cons cell ENDS. |
| 235 | ;; (CDR ENDS) doesn't have to be nil. |
| 236 | ;; - LS2 is some power of two <= LS. |
| 237 | ;; - U is an unsorted list. |
| 238 | ;; - LW is a positive integer. |
| 239 | ;; Starting with S, and taking data from U as needed, produce |
| 240 | ;; a sorted list of *at least* length LW, if there's enough data |
| 241 | ;; (LW <= LS + length(U)), or use all of U if not. |
| 242 | ;; |
| 243 | ;; GROW takes maximal contiguous runs of data from U at a time; |
| 244 | ;; it is allowed to return a list *longer* than LW if it gets lucky |
| 245 | ;; with a long run. |
| 246 | ;; |
| 247 | ;; The key idea: If you want a merge operation to "pay for itself," the two |
| 248 | ;; lists being merged should be about the same length. Remember that. |
| 249 | ;; |
| 250 | ;; Returns: |
| 251 | ;; - A: The result list (not properly terminated) |
| 252 | ;; - ENDA: The last cons cell of the result list. |
| 253 | ;; - LA: The length of the result list |
| 254 | ;; - UNUSED: The unused tail of U. |
| 255 | (define (grow s ends ls ls2 u lw) |
| 256 | (if (and (pair? u) (< ls lw)) |
| 257 | |
| 258 | ;; We haven't met the LW quota but there's still some U data to use. |
| 259 | (mlet (((ls2) (let lp ((ls2 ls2)) |
| 260 | (let ((ls2*2 (+ ls2 ls2))) |
| 261 | (if (<= ls2*2 ls) (lp ls2*2) ls2)))) |
| 262 | ;; LS2 is now the largest power of two <= LS. |
| 263 | ;; (Just think of it as being roughly LS.) |
| 264 | ((lr endr u2) (getrun u)) ; Get a run from U; |
| 265 | ((t endt lt u3) (grow u endr lr 1 u2 ls2)) ; grow it up to be T. |
| 266 | ((st end-st) (merge! s ends t endt))) ; Merge S & T, |
| 267 | (grow st end-st (+ ls lt) (+ ls2 ls2) u3 lw)) ; then loop. |
| 268 | |
| 269 | (values s ends ls u))) ; Done -- met LW quota or ran out of data. |
| 270 | |
| 271 | ;; Note: (LENGTH LIS) or any constant guaranteed |
| 272 | ;; to be greater can be used in place of INFINITY. |
| 273 | (if (pair? lis) |
| 274 | (mlet (((lr endr rest) (getrun lis)) ; Pick off an initial run. |
| 275 | ((infinity) #o100000000) ; Then grow it up maximally. |
| 276 | ((a enda la v) (grow lis endr lr 1 rest infinity))) |
| 277 | (set-cdr! enda '()) ; Nil-terminate answer. |
| 278 | a) ; We're done. |
| 279 | |
| 280 | '())) ; Don't sort an empty list. |
| 281 | |
| 282 | |
| 283 | ;;; Merge |
| 284 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
| 285 | ;;; These two merge procedures are stable -- ties favor list A. |
| 286 | |
| 287 | (define (list-merge < a b) |
| 288 | (cond ((not (pair? a)) b) |
| 289 | ((not (pair? b)) a) |
| 290 | (else (let recur ((x (car a)) (a a) ; A is a pair; X = (CAR A). |
| 291 | (y (car b)) (b b)) ; B is a pair; Y = (CAR B). |
| 292 | (if (< y x) |
| 293 | |
| 294 | (let ((b (cdr b))) |
| 295 | (if (pair? b) |
| 296 | (cons y (recur x a (car b) b)) |
| 297 | (cons y a))) |
| 298 | |
| 299 | (let ((a (cdr a))) |
| 300 | (if (pair? a) |
| 301 | (cons x (recur (car a) a y b)) |
| 302 | (cons x b)))))))) |
| 303 | |
| 304 | |
| 305 | ;;; This destructive merge does as few SET-CDR!s as it can -- for example, if |
| 306 | ;;; the list is already sorted, it does no SET-CDR!s at all. It is also |
| 307 | ;;; iterative, running in constant stack. |
| 308 | |
| 309 | (define (list-merge! < a b) |
| 310 | ;; The logic of these two loops is completely driven by these invariants: |
| 311 | ;; SCAN-A: (CDR PREV) = A. X = (CAR A). Y = (CAR B). |
| 312 | ;; SCAN-B: (CDR PREV) = B. X = (CAR A). Y = (CAR B). |
| 313 | (letrec ((scan-a (lambda (prev a x b y) ; Zip down A doing |
| 314 | (if (< y x) ; no SET-CDR!s until |
| 315 | (let ((next-b (cdr b))) ; we hit a B elt that |
| 316 | (set-cdr! prev b) ; has to be inserted. |
| 317 | (if (pair? next-b) |
| 318 | (scan-b b a x next-b (car next-b)) |
| 319 | (set-cdr! b a))) |
| 320 | |
| 321 | (let ((next-a (cdr a))) |
| 322 | (if (pair? next-a) |
| 323 | (scan-a a next-a (car next-a) b y) |
| 324 | (set-cdr! a b)))))) |
| 325 | |
| 326 | (scan-b (lambda (prev a x b y) ; Zip down B doing |
| 327 | (if (< y x) ; no SET-CDR!s until |
| 328 | (let ((next-b (cdr b))) ; we hit an A elt that |
| 329 | (if (pair? next-b) ; has to be |
| 330 | (scan-b b a x next-b (car next-b)) ; inserted. |
| 331 | (set-cdr! b a))) |
| 332 | |
| 333 | (let ((next-a (cdr a))) |
| 334 | (set-cdr! prev a) |
| 335 | (if (pair? next-a) |
| 336 | (scan-a a next-a (car next-a) b y) |
| 337 | (set-cdr! a b))))))) |
| 338 | |
| 339 | (cond ((not (pair? a)) b) |
| 340 | ((not (pair? b)) a) |
| 341 | |
| 342 | ;; B starts the answer list. |
| 343 | ((< (car b) (car a)) |
| 344 | (let ((next-b (cdr b))) |
| 345 | (if (null? next-b) |
| 346 | (set-cdr! b a) |
| 347 | (scan-b b a (car a) next-b (car next-b)))) |
| 348 | b) |
| 349 | |
| 350 | ;; A starts the answer list. |
| 351 | (else (let ((next-a (cdr a))) |
| 352 | (if (null? next-a) |
| 353 | (set-cdr! a b) |
| 354 | (scan-a a next-a (car next-a) b (car b)))) |
| 355 | a)))) |
| 356 | |
| 357 | |
| 358 | ;;; Copyright |
| 359 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
| 360 | ;;; This code is |
| 361 | ;;; Copyright (c) 1998 by Olin Shivers. |
| 362 | ;;; The terms are: You may do as you please with this code, as long as |
| 363 | ;;; you do not delete this notice or hold me responsible for any outcome |
| 364 | ;;; related to its use. |
| 365 | ;;; |
| 366 | ;;; Blah blah blah. |
| 367 | |
| 368 | |
| 369 | ;;; Code tuning & porting |
| 370 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
| 371 | ;;; This is very portable code. It's R4RS with the following exceptions: |
| 372 | ;;; - The R5RS multiple-value VALUES & CALL-WITH-VALUES procedures for |
| 373 | ;;; handling multiple-value return. |
| 374 | ;;; |
| 375 | ;;; This code is *tightly* bummed as far as I can go in portable Scheme. |
| 376 | ;;; |
| 377 | ;;; - The fixnum arithmetic in LIST-MERGE-SORT! and COUNTED-LIST-MERGE! |
| 378 | ;;; that could be safely switched over to unsafe, fixnum-specific ops, |
| 379 | ;;; if you're sure that 2*maxlen is a fixnum, where maxlen is the length |
| 380 | ;;; of the longest list you could ever have. |
| 381 | ;;; |
| 382 | ;;; - I typically write my code in a style such that every CAR and CDR |
| 383 | ;;; application is protected by an upstream PAIR?. This is the case in this |
| 384 | ;;; code, so all the CAR's and CDR's could safely switched over to unsafe |
| 385 | ;;; versions. But check over the code before you do it, in case the source |
| 386 | ;;; has been altered since I wrote this. |