| 1 | ;;; The SRFI-32 sort package -- 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-sort < v [start end]) -> vector |
| 8 | ;;; (quick-sort! < v [start end]) -> unspecific |
| 9 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
| 10 | ;;; The algorithm is a standard quicksort, but the partition loop is fancier, |
| 11 | ;;; arranging the vector into a left part that is <, a middle region that is |
| 12 | ;;; =, and a right part that is > the pivot. Here's how it is done: |
| 13 | ;;; The partition loop divides the range being partitioned into five |
| 14 | ;;; subranges: |
| 15 | ;;; =======<<<<<<<<<?????????>>>>>>>======= |
| 16 | ;;; where = marks a value that is equal the pivot, < marks a value that |
| 17 | ;;; is less than the pivot, ? marks a value that hasn't been scanned, and |
| 18 | ;;; > marks a value that is greater than the pivot. Let's consider the |
| 19 | ;;; left-to-right scan. If it checks a ? value that is <, it keeps scanning. |
| 20 | ;;; If the ? value is >, we stop the scan -- we are ready to start the |
| 21 | ;;; right-to-left scan and then do a swap. But if the rightward scan checks |
| 22 | ;;; a ? value that is =, we swap it *down* to the end of the initial chunk |
| 23 | ;;; of ====='s -- we exchange it with the leftmost < value -- and then |
| 24 | ;;; continue our rightward scan. The leftwards scan works in a similar |
| 25 | ;;; fashion, scanning past > elements, stopping on a < element, and swapping |
| 26 | ;;; up = elements. When we are done, we have a picture like this |
| 27 | ;;; ========<<<<<<<<<<<<>>>>>>>>>>========= |
| 28 | ;;; Then swap the = elements up into the middle of the vector to get |
| 29 | ;;; this: |
| 30 | ;;; <<<<<<<<<<<<=================>>>>>>>>>> |
| 31 | ;;; Then recurse on the <'s and >'s. Work out all the tricky little |
| 32 | ;;; boundary cases, and you're done. |
| 33 | ;;; |
| 34 | ;;; Other tricks: |
| 35 | ;;; - This quicksort also makes some effort to pick the pivot well -- it uses |
| 36 | ;;; the median of three elements as the partition pivot, so pathological n^2 |
| 37 | ;;; run time is much rarer (but not eliminated completely). If you really |
| 38 | ;;; wanted to get fancy, you could use a random number generator to choose |
| 39 | ;;; pivots. The key to this trick is that you only need to pick one random |
| 40 | ;;; number for each *level* of recursion -- i.e. you only need (lg n) random |
| 41 | ;;; numbers. |
| 42 | ;;; - After the partition, we *recurse* on the smaller of the two pending |
| 43 | ;;; regions, then *tail-recurse* (iterate) on the larger one. This guarantees |
| 44 | ;;; we use no more than lg(n) stack frames, worst case. |
| 45 | ;;; - There are two ways to finish off the sort. |
| 46 | ;;; A Recurse down to regions of size 10, then sort each such region using |
| 47 | ;;; insertion sort. |
| 48 | ;;; B Recurse down to regions of size 10, then sort *the entire vector* |
| 49 | ;;; using insertion sort. |
| 50 | ;;; We do A. Each choice has a cost. Choice A has more overhead to invoke |
| 51 | ;;; all the separate insertion sorts -- choice B only calls insertion sort |
| 52 | ;;; once. But choice B will call the comparison function *more times* -- |
| 53 | ;;; it will unnecessarily compare elt 9 of one segment to elt 0 of the |
| 54 | ;;; following segment. The overhead of choice A is linear in the length |
| 55 | ;;; of the vector, but *otherwise independent of the algorithm's parameters*. |
| 56 | ;;; I.e., it's a *fixed*, *small* constant factor. The cost of the extra |
| 57 | ;;; comparisons made by choice B, however, is dependent on an externality: |
| 58 | ;;; the comparison function passed in by the client. This can be made |
| 59 | ;;; arbitrarily bad -- that is, the constant factor *isn't* fixed by the |
| 60 | ;;; sort algorithm; instead, it's determined by the comparison function. |
| 61 | ;;; If your comparison function is very, very slow, you want to eliminate |
| 62 | ;;; every single one that you can. Choice A limits the potential badness, |
| 63 | ;;; so that is what we do. |
| 64 | |
| 65 | (define (vector-quick-sort! < v . maybe-start+end) |
| 66 | (call-with-values |
| 67 | (lambda () (vector-start+end v maybe-start+end)) |
| 68 | (lambda (start end) |
| 69 | (%quick-sort! < v start end)))) |
| 70 | |
| 71 | (define (vector-quick-sort < v . maybe-start+end) |
| 72 | (call-with-values |
| 73 | (lambda () (vector-start+end v maybe-start+end)) |
| 74 | (lambda (start end) |
| 75 | (let ((ans (make-vector (- end start)))) |
| 76 | (vector-portion-copy! ans v start end) |
| 77 | (%quick-sort! < ans 0 (- end start)) |
| 78 | ans)))) |
| 79 | |
| 80 | ;;; %QUICK-SORT is not exported. |
| 81 | ;;; Preconditions: |
| 82 | ;;; V vector |
| 83 | ;;; START END fixnums |
| 84 | ;;; 0 <= START, END <= (vector-length V) |
| 85 | ;;; If these preconditions are ensured by the cover functions, you |
| 86 | ;;; can safely change this code to use unsafe fixnum arithmetic and vector |
| 87 | ;;; indexing ops, for *huge* speedup. |
| 88 | ;;; |
| 89 | ;;; We bail out to insertion sort for small ranges; feel free to tune the |
| 90 | ;;; crossover -- it's just a random guess. If you don't have the insertion |
| 91 | ;;; sort routine, just kill that branch of the IF and change the recursion |
| 92 | ;;; test to (< 1 (- r l)) -- the code is set up to work that way. |
| 93 | |
| 94 | (define (%quick-sort! elt< v start end) |
| 95 | ;; Swap the N outer pairs of the range [l,r). |
| 96 | (define (swap l r n) |
| 97 | (if (> n 0) |
| 98 | (let ((x (vector-ref v l)) |
| 99 | (r-1 (- r 1))) |
| 100 | (vector-set! v l (vector-ref v r-1)) |
| 101 | (vector-set! v r-1 x) |
| 102 | (swap (+ l 1) r-1 (- n 1))))) |
| 103 | |
| 104 | ;; Choose the median of V[l], V[r], and V[middle] for the pivot. |
| 105 | (define (median v1 v2 v3) |
| 106 | (call-with-values |
| 107 | (lambda () (if (elt< v1 v2) (values v1 v2) (values v2 v1))) |
| 108 | (lambda (little big) |
| 109 | (if (elt< big v3) |
| 110 | big |
| 111 | (if (elt< little v3) v3 little))))) |
| 112 | |
| 113 | (let recur ((l start) (r end)) ; Sort the range [l,r). |
| 114 | (if (< 10 (- r l)) ; Ten: the gospel according to Sedgewick. |
| 115 | |
| 116 | (let ((pivot (median (vector-ref v l) |
| 117 | (vector-ref v (quotient (+ l r) 2)) |
| 118 | (vector-ref v (- r 1))))) |
| 119 | |
| 120 | ;; Everything in these loops is driven by the invariants expressed |
| 121 | ;; in the little pictures & the corresponding l,i,j,k,m,r indices |
| 122 | ;; and the associated ranges. |
| 123 | |
| 124 | ;; =======<<<<<<<<<?????????>>>>>>>======= |
| 125 | ;; l i j k m r |
| 126 | ;; [l,i) [i,j) [j,k] (k,m] (m,r) |
| 127 | (letrec ((lscan (lambda (i j k m) ; left-to-right scan |
| 128 | (let lp ((i i) (j j)) |
| 129 | (if (> j k) |
| 130 | (done i j m) |
| 131 | (let ((x (vector-ref v j))) |
| 132 | (cond ((elt< x pivot) (lp i (+ j 1))) |
| 133 | |
| 134 | ((elt< pivot x) (rscan i j k m)) |
| 135 | |
| 136 | (else ; Equal |
| 137 | (if (< i j) |
| 138 | (begin (vector-set! v j (vector-ref v i)) |
| 139 | (vector-set! v i x))) |
| 140 | (lp (+ i 1) (+ j 1))))))))) |
| 141 | |
| 142 | ;; =======<<<<<<<<<>????????>>>>>>>======= |
| 143 | ;; l i j k m r |
| 144 | ;; [l,i) [i,j) j (j,k] (k,m] (m,r) |
| 145 | (rscan (lambda (i j k m) ; right-to-left scan |
| 146 | (let lp ((k k) (m m)) |
| 147 | (if (<= k j) |
| 148 | (done i j m) |
| 149 | (let* ((x (vector-ref v k))) |
| 150 | (cond ((elt< pivot x) (lp (- k 1) m)) |
| 151 | |
| 152 | ((elt< x pivot) ; Swap j & k & lscan. |
| 153 | (vector-set! v k (vector-ref v j)) |
| 154 | (vector-set! v j x) |
| 155 | (lscan i (+ j 1) (- k 1) m)) |
| 156 | |
| 157 | (else ; x=pivot |
| 158 | (if (< k m) |
| 159 | (begin (vector-set! v k (vector-ref v m)) |
| 160 | (vector-set! v m x))) |
| 161 | (lp (- k 1) (- m 1))))))))) |
| 162 | |
| 163 | |
| 164 | ;; =======<<<<<<<<<<<<<>>>>>>>>>>>======= |
| 165 | ;; l i j m r |
| 166 | ;; [l,i) [i,j) [j,m] (m,r) |
| 167 | (done (lambda (i j m) |
| 168 | (let ((num< (- j i)) |
| 169 | (num> (+ 1 (- m j))) |
| 170 | (num=l (- i l)) |
| 171 | (num=r (- (- r m) 1))) |
| 172 | (swap l j (min num< num=l)) ; Swap ='s into |
| 173 | (swap j r (min num> num=r)) ; the middle. |
| 174 | ;; Recur on the <'s and >'s. Recurring on the |
| 175 | ;; smaller range and iterating on the bigger |
| 176 | ;; range ensures O(lg n) stack frames, worst case. |
| 177 | (cond ((<= num< num>) |
| 178 | (recur l (+ l num<)) |
| 179 | (recur (- r num>) r)) |
| 180 | (else |
| 181 | (recur (- r num>) r) |
| 182 | (recur l (+ l num<)))))))) |
| 183 | |
| 184 | (let ((r-1 (- r 1))) |
| 185 | (lscan l l r-1 r-1)))) |
| 186 | |
| 187 | ;; Small segment => punt to insert sort. |
| 188 | ;; Use the dangerous subprimitive. |
| 189 | (%vector-insert-sort! elt< v l r)))) |
| 190 | |
| 191 |