Last active
August 29, 2015 14:13
-
-
Save dacamo76/725970543e176f601255 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
(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