20-CS-4003-001 |
Organization of Programming Languages |
Fall 2017 |
---|---|---|

Recursion |

**Procedures: Mergesort**

(define split (lambda (l) (if (null? l) (list '() '()) (if (null? (cdr l)) (list l '()) (let ((rest (split (cddr l)))) (list (cons (car l) (car rest)) (cons (car (cdr l)) (car (cdr rest))))))))) (define merge (lambda (l1 l2) (if (null? l1) l2 (if (null? l2) l1 (if (< (car l1) (car l2)) (cons (car l1) (merge (cdr l1) l2)) (cons (car l2) (merge l1 (cdr l2)))))))) (define mrgsrt (lambda (lst) (if (null? lst) '() (if (null? (cdr lst)) lst (let* ((s (split lst)) (a (car s)) (b (cadr s))) (merge (mrgsrt a) (mrgsrt b))))))) | - |
An alternative to the mergesort of the previous slide. This one
splits a list in one pass. Procedure split takes a list of
numbers as input and output a list of two lists of numbers of approximately
equal size such that the set of all numbers in both input lists is the
same as the set of numbers in the input list, including duplicates.
Procedure merge takes two lists of numbers in increasing
order as input and outputs a list of numbers in increasing order consisting
of exactly those numbers in the input lists. Procedure mrgsrt
takes a list of numbers as input and outputs a permutation of that list
where all elements are in increasing order. Example:
prompt> (mrgsrt '(5 8 9 2 3 6 10 3 4 1 7 8)) ;Value 21: (1 2 3 3 4 5 6 7 8 8 9 10) |