Created
July 16, 2015 05:59
-
-
Save douglas-vaz/0ad52921918bad5fa2fd 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 merge-sort) | |
(defn split-at-middle [xs] (split-at (/ (count xs) 2) xs)) | |
(defn merge [X Y] | |
(loop [ [xhead & xtail :as x] X, [yhead & ytail :as y] Y, Result []] | |
(if (and (not-empty x) (not-empty y)) | |
(if (<= xhead yhead) | |
(recur xtail y (conj Result xhead)) | |
(recur x ytail (conj Result yhead))) | |
(concat Result x y)))) | |
(defn merge-sort [xs] | |
(if (or (zero? (count xs)) (= 1 (count xs))) xs | |
(let [[xa xb] (split-at-middle xs)] | |
(merge (merge-sort xa) (merge-sort xb))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment