Sorting by insertion

Exercise 1

Test the insert procedure by inserting a real number

Exercise 2

What happens if ls is not in ascending order when insert is invoked?

Exercise 3

Modify the insert procedure so that it inserts a string into a list of strings that are in alphabetical order:

> (modified-insert "dog" (list "ape" "bear" "cat" "emu" "frog"))
("ape" "bear" "cat" "dog" "emu" "frog")

Exercise 4

Write out a trace of the steps in the evaluation of the procedure call (insertion-sort '(7 6 12 4 10 8 5 1)). The trace should begin like this:

    (insertion-sort '(7 6 12 4 10 8 5 1))
==> (insert 7 (insertion-sort '(6 12 4 10 8 5 1)))
==> (insert 7 (insert 6 (insertion-sort '(12 4 10 8 5 1))))

and should end like this:

==> '(1 4 5 6 7 8 10 12)

Exercise 5

Test the insertion-sort procedure on some potentially troublesome arguments: an empty list, a list containing only one element, a list containing all equal values, a list in which the elements are originally in descending numerical order.

Exercise 6

Figure out how to invoke the generalized version of insertion-sort so that it arranges the strings "bear", "emu", "frog", "ape", "dog", and "cat" into alphabetical order.

Exercise 7

Assemble the full definition of insertion-sort! by editing the definition of insert! into the version given in the reading.

Create and name a vector containing the strings "bear", "emu", "frog", "ape", "dog", and "cat".

Rearrange the elements of the vector into alphabetical order by means of an appropriate call to insertion-sort!. (Note that the sorting occurs as a side effect of this call -- the value of the do-expression in the body of insertion-sort! is unspecified -- so to confirm that the sorting procedure worked you'll have to inspect the vector again afterwards.)


This document is available on the World Wide Web as

http://www.cs.grinnell.edu/~stone/courses/scheme/labs/sorting-by-insertion.xhtml

Validated as XHTML 1.1 by the World Wide Web Consortium Cascading Style Sheet validated by the World Wide Web Consortium

created November 21, 1997
last revised October 10, 2001

John David Stone (stone@cs.grinnell.edu)