(2 3 5 7 9 10 13 18 24)
Given such a list, two common operations involve inserting an item into the
list or removing an item from the list.
;;; procedure to insert an item into a list, where elements are in
;;; ascending order
(define insert-item
(lambda (item ls)
(if (or (null? ls) (<= item (car ls)))
(cons item ls)
(cons (car ls) (insert-item item (cdr ls)))
)
)
)
insert-item
works correctly in inserting the
numbers 1, 9, 11 and 30 into the above list (2 3 5 7 9 10 13 18 24)
.
insert-item
, so that the body contains a named-let
expression that performs the above work using tail recursion.
insert-item
is not
already ordered? For example, what happens if 6 is inserted into the list
(9 7 5 3 1)
?
delete-item
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.
(define insertion-sort
(lambda (ls)
(if (null? ls)
ls
(insert-item (car ls) (insertion-sort (cdr ls)))
)
)
)
(insertion-sort '(3 1 4 1 5 9 2 6 5 3 5))
(insertion-sort '(2 3 5 7 9 10 13 18 24))
(insertion-sort '(24 18 13 10 9 7 5 3 2))
insertion-sort
by changing the
define
to trace-define
.
insert-item
and insertion-sort
, the work could be
define in a single procedure:
(define sort-ascending
(lambda (ls)
(letrec ((insert-item (lambda (item ls)
(if (or (null? ls) (<= item (car ls)))
(cons item ls)
(cons (car ls) (insert-item item (cdr ls)))))))
(if (null? ls)
ls
(insert-item (car ls) (sort-ascending (cdr ls)))
)
)
)
)
letrec
statement.
sort-ascending
, 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.math.grin.edu/~walker/courses/153.sp00/lab-insertion-sort.html