SELECTION SORTING

The selection sorting algorithm really needs a random-access structure, so it is not suitable for lists; moreover, it is much better adapted to rearranging elements within a container than to copying them from an immutable structure into a new, sorted structure. So we'll consider only one version of the selection sort.

The main program is a loop that runs through the positions in the vector from left to right, swapping the least of the remaining unsorted elements into the current position at each step. It stops at the next-to-last position, since the correct occupant of the rightmost position will automatically be swapped into it (with the vector-swap! procedure defined elsewhere).

The internally defined index-of-least-remaining procedure starts at a specified position in the vector v and searches rightwards from that position (that is, through all the higher-numbered positions) for the smallest value -- the least of the unsorted elements of v. It returns the position in which that value is found.

(define selection-sort!
  (lambda (v . opt)

    (let ((precedes? (if (null? opt) < (car opt)))
          (len (vector-length v)))

      (let ((index-of-least-remaining
             (lambda (position)
               (let loop ((least-so-far (vector-ref v position))
                          (index-of-lsf position)
                          (trial-index (+ position 1)))
                 (if (= trial-index len)
                     index-of-lsf
                     (let ((trial-value (vector-ref v trial-index)))
                       (if (precedes? trial-value least-so-far)
                           (loop trial-value
                                 trial-index
                                 (+ trial-index 1))
                           (loop least-so-far
                                 index-of-lsf
                                 (+ trial-index 1)))))))))

        (do ((index 0 (+ index 1)))
            ((= index (- len 1)))
          (vector-swap! v
                        index
                        (index-of-least-remaining index)))))))


This document is available on the World Wide Web as

http://www.math.grin.edu/~stone/events/scheme-workshop/selection.html


created July 11, 1995
last revised June 25, 1996

John David Stone (stone@math.grin.edu)