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

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures        Code

Procedures: Mergesort

(define merge
  (lambda (x y)
    (if (null? x)
        y
        (if (null? y)
            x
            (if (< (car x) (car y))
                (cons (car x) (merge (cdr x) y))
                (cons (car y) (merge x (cdr y))))))))

(define splite
  (lambda (x)
    (if (or (null? x) (null? (cdr x)))
        x
        (cons (car x) (splite (cdr (cdr x)))))))

(define splito
  (lambda (x)
    (if (or (null? x) (null? (cdr x)))
        '()
        (cons (car (cdr x)) (splito (cdr (cdr x)))))))

(define mrgsrt
  (lambda (lst)
    (if (or (null? lst) (null? (cdr lst)))
        lst
        (merge (mrgsrt (splito lst))
               (mrgsrt (splite lst))))))
 -  Classic mergesort program. Given a list lst of integers, return a list containing a permutation of lst where elements are in increasing order. Example:
  prompt> (mrgsrt '(9 4 23 16 12 42 77 28))
  ;Value 11: (4 9 12 16 23 28 42 77)