Last active
May 8, 2016 11:06
-
-
Save zehnpaard/6f49bab84162262048beae83c211a921 to your computer and use it in GitHub Desktop.
Clojure Merge Sort using lazy-seq and partition-all
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 merge-sorted | |
"Merge two sorted sequences into one sorted sequence | |
If called with one sequence as argument, return the sequence unchanged" | |
([xs] xs) | |
([[head1 & tail1 :as xs1] [head2 & tail2 :as xs2]] | |
(cond | |
(some empty? [xs1 xs2]) | |
(concat xs1 xs2) | |
(< head1 head2) | |
(lazy-seq (cons head1 (merge-sorted tail1 xs2))) | |
:else | |
(lazy-seq (cons head2 (merge-sorted xs1 tail2)))))) | |
(defn merge-sort | |
"Sort sequence using tail-recursive application of merge" | |
[xs] | |
(loop [list-seq (map list xs)] | |
(if (empty? (rest list-seq)) | |
(first list-seq) | |
(recur (map #(apply merge-sorted %) (partition-all 2 list-seq)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment