Created
October 1, 2012 15:04
-
-
Save emdeesee/3812319 to your computer and use it in GitHub Desktop.
Merge Sort in Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn merge-sort | |
"Produce a sorted sequence from an input sequence. Sort into ascending order by default, or use optional comparison function." | |
([x] (merge-sort < x)) | |
([swo x] | |
(letfn [(merge [left right] | |
(loop [l left r right result []] | |
(let [l-first (first l) r-first (first r)] | |
(cond (nil? l-first) (concat result r) | |
(nil? r-first) (concat result l) | |
:default (if (swo l-first r-first) | |
(recur (rest l) r (conj result l-first)) | |
(recur l (rest r) (conj result r-first))))))) | |
(sort [coll] | |
(let [c (count coll)] | |
(if (< c 2) | |
coll | |
(let [h (/ c 2)] | |
(apply merge (map sort (split-at h coll)))))))] | |
(sort x)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment