Skip to content

Instantly share code, notes, and snippets.

@egri-nagy
Created May 10, 2015 23:57
Show Gist options
  • Save egri-nagy/512998bd8482fc49947b to your computer and use it in GitHub Desktop.
Save egri-nagy/512998bd8482fc49947b to your computer and use it in GitHub Desktop.
Merge sort in Clojure in a single function
(defn merge-sort
"sorting the given collection with merge-sort"
[coll]
(if (or (empty? coll) (= 1 (count coll)))
coll
(let [[l1 l2] (split-at (/ (count coll) 2) coll)]
;recursive call
(loop [r [] l1 (merge-sort l1) l2 (merge-sort l2)]
;merging
(cond (empty? l1) (into r l2) ;when l1 is exhausted
(empty? l2) (into r l1) ;when l2 is exhausted
:else (if (> 0 (compare (first l1) (first l2))) ;comparison
(recur (conj r (first l1)) (rest l1) l2)
(recur (conj r (first l2)) l1 (rest l2))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment