Skip to content

Instantly share code, notes, and snippets.

@emdeesee
Created October 1, 2012 15:04
Show Gist options
  • Save emdeesee/3812319 to your computer and use it in GitHub Desktop.
Save emdeesee/3812319 to your computer and use it in GitHub Desktop.
Merge Sort in Clojure
(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