Skip to content

Instantly share code, notes, and snippets.

@zehnpaard
Last active May 8, 2016 11:06
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 zehnpaard/6f49bab84162262048beae83c211a921 to your computer and use it in GitHub Desktop.
Save zehnpaard/6f49bab84162262048beae83c211a921 to your computer and use it in GitHub Desktop.
Clojure Merge Sort using lazy-seq and partition-all
(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