Skip to content

Instantly share code, notes, and snippets.

@podviaznikov
Last active Dec 26, 2015
Embed
What would you like to do?
Merge sort implementation in Clojure. Merge step is recursive itself!
(defn mergestep [l r op]
(cond (empty? l) r
(empty? r) l
:else
(let [fl (first l)
fr (first r)]
(if (op fl fr)
(cons fl (mergestep (rest l) r op))
(cons fr (mergestep l (rest r) op))))))
(defn mergesort
([data]
(mergesort data <))
([data op]
(if (< (count data) 2)
data
(let [halfsize (/ (count data) 2)
split (split-at halfsize data)
left (first split)
right (second split)
result (mergestep (mergesort left op) (mergesort right op) op)]
result))))
(mergesort '(7 8 12 2 3 45)) ; (2 3 7 8 12 45)
(mergesort '(7 8 12 2 3 45) >) ; (45 12 8 7 3 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment