| 1 | ;;; The SRFI-32 sort package -- three-way quick sort -*- Scheme -*- |
| 2 | ;;; Copyright (c) 2002 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 2002/7. |
| 6 | |
| 7 | ;;; (quick-sort3! c v [start end]) -> unspecific |
| 8 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
| 9 | ;;; Sort vector V[start,end) using three-way comparison function C: |
| 10 | ;;; (c x y) < 0 => x<y |
| 11 | ;;; (c x y) = 0 => x=y |
| 12 | ;;; (c x y) > 0 => x>y |
| 13 | ;;; That is, C acts as a sort of "subtraction" procedure; using - for the |
| 14 | ;;; comparison function will cause numbers to be sorted into increasing order. |
| 15 | ;;; |
| 16 | ;;; This algorithm is more efficient than standard, two-way quicksort if there |
| 17 | ;;; are many duplicate items in the data set and the comparison function is |
| 18 | ;;; relatively expensive (e.g., comparing large strings). It is due to Jon |
| 19 | ;;; Bentley & Doug McIlroy; I learned it from Bentley. |
| 20 | ;;; |
| 21 | ;;; The algorithm is a standard quicksort, but the partition loop is fancier, |
| 22 | ;;; arranging the vector into a left part that is <, a middle region that is |
| 23 | ;;; =, and a right part that is > the pivot. Here's how it is done: |
| 24 | ;;; The partition loop divides the range being partitioned into five |
| 25 | ;;; subranges: |
| 26 | ;;; =======<<<<<<<<<?????????>>>>>>>======= |
| 27 | ;;; where = marks a value that is equal the pivot, < marks a value that |
| 28 | ;;; is less than the pivot, ? marks a value that hasn't been scanned, and |
| 29 | ;;; > marks a value that is greater than the pivot. Let's consider the |
| 30 | ;;; left-to-right scan. If it checks a ? value that is <, it keeps scanning. |
| 31 | ;;; If the ? value is >, we stop the scan -- we are ready to start the |
| 32 | ;;; right-to-left scan and then do a swap. But if the rightward scan checks |
| 33 | ;;; a ? value that is =, we swap it *down* to the end of the initial chunk |
| 34 | ;;; of ====='s -- we exchange it with the leftmost < value -- and then |
| 35 | ;;; continue our rightward scan. The leftwards scan works in a similar |
| 36 | ;;; fashion, scanning past > elements, stopping on a < element, and swapping |
| 37 | ;;; up = elements. When we are done, we have a picture like this |
| 38 | ;;; ========<<<<<<<<<<<<>>>>>>>>>>========= |
| 39 | ;;; Then swap the = elements up into the middle of the vector to get |
| 40 | ;;; this: |
| 41 | ;;; <<<<<<<<<<<<=================>>>>>>>>>> |
| 42 | ;;; Then recurse on the <'s and >'s. Work out all the tricky little |
| 43 | ;;; boundary cases, and you're done. |
| 44 | ;;; |
| 45 | ;;; Other tricks that make this implementation industrial strength: |
| 46 | ;;; - This quicksort makes some effort to pick the pivot well -- it uses the |
| 47 | ;;; median of three elements as the partition pivot, so pathological n^2 |
| 48 | ;;; run time is much rarer (but not eliminated completely). If you really |
| 49 | ;;; wanted to get fancy, you could use a random number generator to choose |
| 50 | ;;; pivots. The key to this trick is that you only need to pick one random |
| 51 | ;;; number for each *level* of recursion -- i.e. you only need (lg n) random |
| 52 | ;;; numbers. |
| 53 | ;;; |
| 54 | ;;; - After the partition, we *recurse* on the smaller of the two pending |
| 55 | ;;; regions, then *tail-recurse* (iterate) on the larger one. This guarantees |
| 56 | ;;; we use no more than lg(n) stack frames, worst case. |
| 57 | ;;; |
| 58 | ;;; - There are two ways to finish off the sort. |
| 59 | ;;; A. Recurse down to regions of size 10, then sort each such region using |
| 60 | ;;; insertion sort. |
| 61 | ;;; B. Recurse down to regions of size 10, then sort *the entire vector* |
| 62 | ;;; using insertion sort. |
| 63 | ;;; We do A. Each choice has a cost. Choice A has more overhead to invoke |
| 64 | ;;; all the separate insertion sorts -- choice B only calls insertion sort |
| 65 | ;;; once. But choice B will call the comparison function *more times* -- |
| 66 | ;;; it will unnecessarily compare elt 9 of one segment to elt 0 of the |
| 67 | ;;; following segment. The overhead of choice A is linear in the length |
| 68 | ;;; of the vector, but *otherwise independent of the algorithm's parameters*. |
| 69 | ;;; I.e., it's a *fixed*, *small* constant factor. The cost of the extra |
| 70 | ;;; comparisons made by choice B, however, is dependent on an externality: |
| 71 | ;;; the comparison function passed in by the client. This can be made |
| 72 | ;;; arbitrarily bad -- that is, the constant factor *isn't* fixed by the |
| 73 | ;;; sort algorithm; instead, it's determined by the comparison function. |
| 74 | ;;; If your comparison function is very, very slow, you want to eliminate |
| 75 | ;;; every single one that you can. Choice A limits the potential badness, |
| 76 | ;;; so that is what we do. |
| 77 | |
| 78 | (define (vector-quick-sort3! c v . maybe-start+end) |
| 79 | (call-with-values |
| 80 | (lambda () (vector-start+end v maybe-start+end)) |
| 81 | (lambda (start end) |
| 82 | (%quick-sort3! c v start end)))) |
| 83 | |
| 84 | (define (vector-quick-sort3 c v . maybe-start+end) |
| 85 | (call-with-values |
| 86 | (lambda () (vector-start+end v maybe-start+end)) |
| 87 | (lambda (start end) |
| 88 | (let ((ans (make-vector (- end start)))) |
| 89 | (vector-portion-copy! ans v start end) |
| 90 | (%quick-sort3! c ans 0 (- end start)) |
| 91 | ans)))) |
| 92 | |
| 93 | ;;; %QUICK-SORT3! is not exported. |
| 94 | ;;; Preconditions: |
| 95 | ;;; V vector |
| 96 | ;;; START END fixnums |
| 97 | ;;; 0 <= START, END <= (vector-length V) |
| 98 | ;;; If these preconditions are ensured by the cover functions, you |
| 99 | ;;; can safely change this code to use unsafe fixnum arithmetic and vector |
| 100 | ;;; indexing ops, for *huge* speedup. |
| 101 | ;;; |
| 102 | ;;; We bail out to insertion sort for small ranges; feel free to tune the |
| 103 | ;;; crossover -- it's just a random guess. If you don't have the insertion |
| 104 | ;;; sort routine, just kill that branch of the IF and change the recursion |
| 105 | ;;; test to (< 1 (- r l)) -- the code is set up to work that way. |
| 106 | |
| 107 | (define (%quick-sort3! c v start end) |
| 108 | (define (swap l r n) ; Little utility -- swap the N |
| 109 | (if (> n 0) |
| 110 | (let ((x (vector-ref v l)) ; outer pairs of the range [l,r). |
| 111 | (r-1 (- r 1))) |
| 112 | (vector-set! v l (vector-ref v r-1)) |
| 113 | (vector-set! v r-1 x) |
| 114 | (swap (+ l 1) r-1 (- n 1))))) |
| 115 | |
| 116 | (define (sort3 v1 v2 v3) |
| 117 | (call-with-values |
| 118 | (lambda () (if (< (c v1 v2) 0) (values v1 v2) (values v2 v1))) |
| 119 | (lambda (little big) |
| 120 | (if (< (c big v3) 0) |
| 121 | (values little big v3) |
| 122 | (if (< (c little v3) 0) |
| 123 | (values little v3 big) |
| 124 | (values v3 little big)))))) |
| 125 | |
| 126 | (define (elt< v1 v2) |
| 127 | (negative? (c v1 v2))) |
| 128 | |
| 129 | (let recur ((l start) (r end)) ; Sort the range [l,r). |
| 130 | (if (< 10 (- r l)) ; 10: the gospel according to Sedgewick. |
| 131 | |
| 132 | ;; Choose the median of V[l], V[r-1], and V[middle] for the pivot. |
| 133 | ;; We do this by sorting these three elts; call the results LO, PIVOT |
| 134 | ;; & HI. Put LO, PIVOT & HI where they should go in the vector. We |
| 135 | ;; will kick off the partition step with one elt (PIVOT) in the left= |
| 136 | ;; range, one elt (LO) in the < range, one elt (HI) in in the > range |
| 137 | ;; & no elts in the right= range. |
| 138 | (let* ((r-1 (- r 1)) ; Three handy |
| 139 | (mid (quotient (+ l r) 2)) ; common |
| 140 | (l+1 (+ l 1)) ; subexpressions |
| 141 | (pivot (call-with-values |
| 142 | (lambda () |
| 143 | (sort3 (vector-ref v l) |
| 144 | (vector-ref v mid) |
| 145 | (vector-ref v r-1))) |
| 146 | (lambda (lo piv hi) |
| 147 | (let ((tmp (vector-ref v l+1))) ; Put LO, PIV & HI |
| 148 | (vector-set! v l piv) ; back into V |
| 149 | (vector-set! v r-1 hi) ; where they belong, |
| 150 | (vector-set! v l+1 lo) |
| 151 | (vector-set! v mid tmp) |
| 152 | piv))))) ; and return PIV as pivot. |
| 153 | |
| 154 | |
| 155 | ;; Everything in these loops is driven by the invariants expressed |
| 156 | ;; in the little pictures, the corresponding l,i,j,k,m,r indices, |
| 157 | ;; & the associated ranges. |
| 158 | |
| 159 | ;; =======<<<<<<<<<?????????>>>>>>>======= (picture) |
| 160 | ;; l i j k m r (indices) |
| 161 | ;; [l,i) [i,j) [j,k] (k,m] (m,r) (ranges ) |
| 162 | (letrec ((lscan (lambda (i j k m) ; left-to-right scan |
| 163 | (let lp ((i i) (j j)) |
| 164 | (if (> j k) |
| 165 | (done i j m) |
| 166 | (let* ((x (vector-ref v j)) |
| 167 | (sign (c x pivot))) |
| 168 | (cond ((< sign 0) (lp i (+ j 1))) |
| 169 | |
| 170 | ((= sign 0) |
| 171 | (if (< i j) |
| 172 | (begin (vector-set! v j (vector-ref v i)) |
| 173 | (vector-set! v i x))) |
| 174 | (lp (+ i 1) (+ j 1))) |
| 175 | |
| 176 | ((> sign 0) (rscan i j k m)))))))) |
| 177 | |
| 178 | ;; =======<<<<<<<<<>????????>>>>>>>======= |
| 179 | ;; l i j k m r |
| 180 | ;; [l,i) [i,j) j (j,k] (k,m] (m,r) |
| 181 | (rscan (lambda (i j k m) ; right-to-left scan |
| 182 | (let lp ((k k) (m m)) |
| 183 | (if (<= k j) |
| 184 | (done i j m) |
| 185 | (let* ((x (vector-ref v k)) |
| 186 | (sign (c x pivot))) |
| 187 | (cond ((> sign 0) (lp (- k 1) m)) |
| 188 | |
| 189 | ((= sign 0) |
| 190 | (if (< k m) |
| 191 | (begin (vector-set! v k (vector-ref v m)) |
| 192 | (vector-set! v m x))) |
| 193 | (lp (- k 1) (- m 1))) |
| 194 | |
| 195 | ((< sign 0) ; Swap j & k & lscan. |
| 196 | (vector-set! v k (vector-ref v j)) |
| 197 | (vector-set! v j x) |
| 198 | (lscan i (+ j 1) (- k 1) m)))))))) |
| 199 | |
| 200 | ;; =======<<<<<<<<<<<<<>>>>>>>>>>>======= |
| 201 | ;; l i j m r |
| 202 | ;; [l,i) [i,j) [j,m] (m,r) |
| 203 | (done (lambda (i j m) |
| 204 | (let ((num< (- j i)) |
| 205 | (num> (+ 1 (- m j))) |
| 206 | (num=l (- i l)) |
| 207 | (num=r (- (- r m) 1))) |
| 208 | (swap l j (min num< num=l)) ; Swap ='s into |
| 209 | (swap j r (min num> num=r)) ; the middle. |
| 210 | ;; Recur on the <'s and >'s. Recurring on the |
| 211 | ;; smaller range and iterating on the bigger |
| 212 | ;; range ensures O(lg n) stack frames, worst case. |
| 213 | (cond ((<= num< num>) |
| 214 | (recur l (+ l num<)) |
| 215 | (recur (- r num>) r)) |
| 216 | (else |
| 217 | (recur (- r num>) r) |
| 218 | (recur l (+ l num<)))))))) |
| 219 | |
| 220 | ;; To repeat: We kick off the partition step with one elt (PIVOT) |
| 221 | ;; in the left= range, one elt (LO) in the < range, one elt (HI) |
| 222 | ;; in the > range & no elts in the right= range. |
| 223 | (lscan l+1 (+ l 2) (- r 2) r-1))) |
| 224 | |
| 225 | ;; Small segment => punt to insert sort. |
| 226 | ;; Use the dangerous subprimitive. |
| 227 | (%vector-insert-sort! elt< v l r)))) |
| 228 | |
| 229 | ;;; Copyright |
| 230 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
| 231 | ;;; This code is |
| 232 | ;;; Copyright (c) 1998 by Olin Shivers. |
| 233 | ;;; The terms are: You may do as you please with this code, as long as |
| 234 | ;;; you do not delete this notice or hold me responsible for any outcome |
| 235 | ;;; related to its use. |
| 236 | ;;; |
| 237 | ;;; Blah blah blah. |
| 238 | |
| 239 | |
| 240 | ;;; Code tuning & porting |
| 241 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
| 242 | ;;; - The quicksort recursion bottoms out in a call to an insertion sort |
| 243 | ;;; routine, %INSERT-SORT!. But you could even punt this and go with pure |
| 244 | ;;; recursion in a pinch. |
| 245 | ;;; |
| 246 | ;;; This code is *tightly* bummed as far as I can go in portable Scheme. |
| 247 | ;;; |
| 248 | ;;; The internal primitive %QUICK-SORT! that does the real work can be |
| 249 | ;;; converted to use unsafe vector-indexing and fixnum-specific arithmetic ops |
| 250 | ;;; *if* you alter the two small cover functions to enforce the invariants. |
| 251 | ;;; This should provide *big* speedups. In fact, all the code bumming I've |
| 252 | ;;; done pretty much disappears in the noise unless you have a good compiler |
| 253 | ;;; and also can dump the vector-index checks and generic arithmetic -- so |
| 254 | ;;; I've really just set things up for you to exploit. |
| 255 | ;;; |
| 256 | ;;; The optional-arg parsing, defaulting, and error checking is done with a |
| 257 | ;;; portable R4RS macro. But if your Scheme has a faster mechanism (e.g., |
| 258 | ;;; Chez), you should definitely port over to it. Note that argument defaulting |
| 259 | ;;; and error-checking are interleaved -- you don't have to error-check |
| 260 | ;;; defaulted START/END args to see if they are fixnums that are legal vector |
| 261 | ;;; indices for the corresponding vector, etc. |