Skip to content

Instantly share code, notes, and snippets.

@douglas-vaz
Created July 16, 2015 05:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save douglas-vaz/0ad52921918bad5fa2fd to your computer and use it in GitHub Desktop.
Save douglas-vaz/0ad52921918bad5fa2fd to your computer and use it in GitHub Desktop.
Merge sort in Clojure
(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