Last active
December 26, 2015 06:29
-
-
Save podviaznikov/7107898 to your computer and use it in GitHub Desktop.
Merge sort implementation in Clojure.
Merge step is recursive itself!
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
(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