Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clean merge sort code #1

Open
GHolk opened this issue Apr 19, 2018 · 0 comments
Open

clean merge sort code #1

GHolk opened this issue Apr 19, 2018 · 0 comments

Comments

@GHolk
Copy link

GHolk commented Apr 19, 2018

usage: (merge-sort '(2 1 8 3 2 5 7 9 4 6 9))
merge 和 split-list 是尾端遞迴,
可能爆 stack 是 merge-sort 本身會是 2^n 。

(defun merge (merge-list sort1 sort2)
  (cond
   ((null sort1) (append (reverse merge-list) sort2))
   ((null sort2) (append (reverse merge-list) sort1))
   (t (let ((a1 (car sort1))
            (a2 (car sort2)))
        (if (< a1 a2)
            (merge (cons a1 merge-list)
                   (cdr sort1)
                   sort2)
          (merge (cons a2 merge-list)
                 sort1
                 (cdr sort2)))))))


(defun split-list (list1 list2)
  (if (>= (length list1)
         (length list2))
      (cons list1 list2)
    (split-list (cons (car list2) list1)
                (cdr list2))))
      
(defun merge-sort (list)
  (let ((list-length (length list)))
    (if (= list-length 1)
        list
      (let* ((pair (split-list '() list))
             (list1 (car pair))
             (list2 (cdr pair)))
        (merge (merge-sort list1)
               (merge-sort list2))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant