CSC 153  Grinnell College  Spring, 2005 
Computer Science Fundamentals  
Laboratory Exercise  
This laboratory exercise provides practice in defining and using the insertion sort as a mechanism to order numbers on a list.
Consider the following code that inserts an item into an ordered list, ensuring that the new list remains ordered:
;;; procedure to insert an item into a list, where elements are in
;;; ascending order
(define insertitem
(lambda (item ls)
(if (or (null? ls) (<= item (car ls)))
(cons item ls)
(cons (car ls) (insertitem item (cdr ls)))
)
)
)
insertitem
works correctly in inserting the
numbers 1, 9, 11 and 30 into the list (2 3 5 7 9 10 13 18 24)
.
insertitem
, so that the body contains a namedlet
expression that performs the above work using tail recursion.
insertitem
is not
already ordered? For example, what happens if 6 is inserted into the list
(9 7 5 3 1)
?
deleteitem
which removes one copy of a
designated item from an ordered list. If the item is not present on the
list, return an error. In your code, use the ordering of the list to
minimize the amount of searching through the list.
The following procedure uses the insertitem to successively build up an ordered list of values.
(define insertionsort
(lambda (ls)
(if (null? ls)
ls
(insertitem (car ls) (insertionsort (cdr ls)))
)
)
)
(insertionsort '(3 1 4 1 5 9 2 6 5 3 5))
(insertionsort '(2 3 5 7 9 10 13 18 24))
(insertionsort '(24 18 13 10 9 7 5 3 2))
insertionsort
by changing the
define
to tracedefine
.
The following procedure combines the procedures, insertitem
and insertionsort
, witin a single procedure:
(define sortascending
(lambda (ls)
(letrec ((insertitem (lambda (item ls)
(if (or (null? ls) (<= item (car ls)))
(cons item ls)
(cons (car ls) (insertitem item (cdr ls)))))))
(if (null? ls)
ls
(insertitem (car ls) (sortascending (cdr ls)))
)
)
)
)
letrec
statement.
sortascending
, so that the list is sorted in descending
order rather than ascending order.
This document is available on the World Wide Web as
http://www.cs.grinnell.edu/~walker/courses/153.sp05/labs/labinsertionsort.shtml
created March 8, 1998 last revised February 3, 2005 

For more information, please contact Henry M. Walker at walker@cs.grinnell.edu. 