; Background: ; What is quicksort? ; A sorting algorithm, puts the elements of a vector ; in order ; We've done list-based quicksort ; Divide-and-conquer algorithm ; Select a "random" pivot ; Divide into smaller, equal, greater ; Recurse ; What do we expect to do with array-based quicksort? ; Similar to list-based ; Except "p(vearts of an array" are different ; How do you keep track of "part of an array" in ; binary search? Index of lower-bound and ; upper bound of that portion. (define partition! (let ((swap! (lambda (vec i j) (let ((tmp (vector-ref vec i))) (vector-set! vec i (vector-ref vec j)) (vector-set! vec j tmp))))) (lambda (vec lower upper can-come-before?) (if (= lower upper) lower (begin (swap! vec lower (+ lower (random (- (+ 1 upper) lower)))) (let kernel! ((l lower) (u upper)) (cond ((= u l) (begin (swap! vec lower u) u)) ((not (can-come-before? (vector-ref vec u) (vector-ref vec lower))) (kernel! l (- u 1))) ((can-come-before? (vector-ref vec l) (vector-ref vec lower)) (kernel! (+ l 1) u)) (else (begin (swap! vec l u) (kernel! l u)))))))))) (define quicksort! (lambda (vec can-come-before?) (quicksort-helper! vec can-come-before? 0 (-(vector-length vec) 1)))) (define quicksort-helper! (lambda (vec can-come-before? lower upper) (if (> upper lower) (let ((pivotloc (partition! vec lower upper can-come-before?)) ) (begin (quicksort-helper! vec can-come-before? lower (- pivotloc 1)) (quicksort-helper! vec can-come-before? (+ pivotloc 1) upper))))))