merge sort in scheme
merge sort的思想很简单,首先将表均匀分成2份,然后每份都是递归使用merge sort来排序,最后使用一个线性合并的方法来合并两个有序表。
为此我们首先定义的是split-evenly,用来切分一个list
(define (split-evenly lst)
(if (null? lst) (list '() '()) ;空表的话返回两个空表
(let* ((h (car lst)) (rest (cdr lst)) (len (length lst)) (sp (split-evenly rest)) (first (car sp)) (second (cadr sp)))
(if (= (remainder len 2) 0)
(list (cons h first) second)
(list first (cons h second))))))
这个历程就是讲一个表拆分成为两个表,下一个历程是将两个有序表合并成为一个表
(define (merge-sorted-list p lst-1 lst-2)
(cond ((null? lst-1) lst-2)
((null? lst-2) lst-1)
((p (car lst-1) (car lst-2)) (cons (car lst-1) (merge-sorted-list p (cdr lst-1) lst-2)))
(else (cons (car lst-2) (merge-sorted-list p ls-1 (cdr lst-2))))))
有了这两个辅助函数以后,merge sort就是水到渠成了
(define (merge-sort p lst)
(if (or (null? lst) (= (length lst) 1)) lst
(let* ((sp (split-evenly lst))
(first (car sp))
(second (cadr sp))
(merge-sorted-list p (merge-sort p first) (merge-sort p second)))))
简单测试都是可以通过的。