Skip to content

Instantly share code, notes, and snippets.

@dacamo76
Last active August 29, 2015 14:13
Show Gist options
  • Save dacamo76/725970543e176f601255 to your computer and use it in GitHub Desktop.
Save dacamo76/725970543e176f601255 to your computer and use it in GitHub Desktop.
merge sort in Clojure
(ns sort.merge)
(defn combine
"Combines sorted collections c1 and c2"
[c1 c2]
(loop [a c1 b c2 sorted []]
(if (some empty? [a b])
(concat sorted a b)
(if (<= (first a) (first b))
(recur (rest a) b (conj sorted (first a)))
(recur a (rest b) (conj sorted (first b)))))))
(defn merge-sort
[x]
(let [n (count x)
[left right] (split-at (/ n 2) x)]
(if (== n 1)
x
(combine (merge-sort left) (merge-sort right)))))
(defn -main
"Reads in file with a number on each line and outputs sorted list."
[& args]
(let [unsorted (-> args first clojure.java.io/reader line-seq)]
(doseq [number (merge-sort (map read-string unsorted))]
(println number))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment