Skip to content

Instantly share code, notes, and snippets.

@cleac
Created May 30, 2017 06:44
Show Gist options
  • Save cleac/4355da18f88ae4f53e5cb1fab18839f5 to your computer and use it in GitHub Desktop.
Save cleac/4355da18f88ae4f53e5cb1fab18839f5 to your computer and use it in GitHub Desktop.
Merge sort implementation in lisp
(defun merge-sort(lst)
(defun merge_(f s)
(cond
((= (list-length f) 0) s)
((= (list-length s) 0) f)
((< (car f) (car s)) (append (list (car f)) (merge_ (cdr f) s)))
((> (car f) (car s)) (append (list (car s)) (merge_ f (cdr s))))
((= (car f) (car s)) (append (list (car f) (car s)) (merge_ (cdr f) (cdr s))))
)
)
(let ((len (list-length lst)))
(cond
((= len 1) lst)
(t
(merge_ (merge-sort (subseq lst 0 (ceiling (/ len 2))))
(merge-sort (subseq lst (ceiling (/ len 2))))
)
)
)
)
)
@lispm
Copy link

lispm commented May 30, 2017

Some hints how to write more idiomatic Lisp code...

; DEFUN is not for nested functions. Use LABELS or FLET. Use LABELS for recursive functions.
; Don't use LIST-LENGTH to check for an empty list. Use NULL.
; Instead of CAR/CDR use FIRST/REST for list operations.
; Don't use APPEND, use LIST*.
; You can use CEILING with a divisor, no need to use /.
; You can also name the variable LIST, not LST. There are no name
;   conflicts between variables and functions in Common Lisp.
; Don't put ) alone on lines. The parentheses like company.

(defun merge-sort (list)
  (labels ((merge-aux (f s)
             (cond
              ((null f) s)
              ((null s) f)
              ((< (first f) (first s)) (list* (first f) (merge-aux (rest f) s)))
              ((> (first f) (first s)) (list* (first s) (merge-aux f (rest s))))
              ((= (first f) (first s)) (list* (first f)
                                              (first s)
                                              (merge-aux (rest f) (rest s)))))))
    (let ((len (list-length list)))
      (if (<= len 1)
          list
        (merge-aux (merge-sort (subseq list 0 (ceiling len 2)))
                   (merge-sort (subseq list (ceiling len 2))))))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment