To understand how this works, try passing the list '(3 7 6 1 5 2 4) into mergesort and trace the mergesort function. You can do this by using:
(require (lib "trace.ss"))
in DrScheme and then, after copying and pasting in the mergesort code, do:
(trace mergesort)
Below is a fully functional mergesort in Scheme:
(define (mergesort l) (cond ((< (length l) 2) l) (else (merge (mergesort (partition1 l)) (mergesort (partition2 l)))))) (define (merge l1 l2) (cond ((null? l1) l2) ((null? l2) l1) ((< (car l1) (car l2)) (cons (car l1) (merge (cdr l1) l2))) (else (cons (car l2) (merge l1 (cdr l2)))))) (define (partition1 l) (let ((num-elements (round (/ (length l) 2)))) (define (part counter l) (cond ((= counter num-elements) '()) (else (cons (car l) (part (+ counter 1) (cdr l)))))) (part 0 l))) (define (partition2 l) (let ((num-elements (round (/ (length l) 2)))) (define (part counter l) (cond ((= counter num-elements) l) (else (part (+ counter 1) (cdr l))))) (part 0 l)))