Homework 18: Selection Sort

Assigned: Tuesday, April 24, 2007
Due: Friday, April 27, 2007

Summary: In this assignment, you will explore another sorting algorithm, selection sort.

Purpose: To help you think more about sorting.

Expected Time: One to two hours.

Collaboration: You may work in a group of any size between one and four, inclusive. You may consult others outside your group, provided you cite those others. You need only submit one assignment per group.

Submitting: Email me your work, using a subject of CSC151 Homework 18.

Warning: So that this exercise is a learning assignment for everyone, I may spend class time publicly critiquing your work.


Background: Selection Sort

As you may recall from our in-class discussion of sorting techniques, one popular strategy for sorting involves repeatedly finding the smallest remaining value in a vector and then putting it after the things that are already sorted. We call this procedure selection sort because the primary operation is selecting the smallest remaining value.

The process is fairly straightforward. For example, in a vector of 10 elements, selection sort

As that example suggests, a key helper for selection sort is finding the index of the smallest value in a subvector. We might document that procedure as follows:

;;; Procedure:
;;; index-of-smallest
;;; Parameters:
;;; vec, a vector
;;; may-precede?, a binary predicate
;;; start-index, an integer
;;; Purpose:
;;; Find the index of the smallest value in vec, starting
;;; with start-index.
;;; Produces:
;;; ios, an integer
;;; Preconditions:
;;; may-precede? is transitive and reflexive.
;;; 0 <= start-index < (vector-length vec)
;;; Postconditions:
;;; start-index <= ios < (vector-length vec)
;;; For all i >= start-index and not equal to ios,
;;; (may-precede? (vector-ref vec ios) (vector-ref vec i))

Assignment

a. Implement index-of-smallest.

b. Implement (swap! vec i j), a procedure that swaps the values at positions i and j of vec.

c. Using index-of-smallest and swap!, implement selection-sort!. Note that you will probably want to iterate over the position in the vector.


Janet Davis (davisjan@cs.grinnell.edu)

Created April 23, 2007 based on http://www.cs.grinnell.edu/~davisjan/csc/151/2006F/homework/16.selection-sort.html
Last revised
April 23, 2007
With thanks to Sam Rebelsky