Skip to content

Instantly share code, notes, and snippets.

@michalmarczyk
Created May 1, 2012 03:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michalmarczyk/2564705 to your computer and use it in GitHub Desktop.
Save michalmarczyk/2564705 to your computer and use it in GitHub Desktop.
Multiway merge of sorted sequences
(defn merge-sorted [comparator & xss]
(let [xss (into-array Object (remove empty? xss))
pq (java.util.PriorityQueue.
(count xss) #(comparator (val %1) (val %2)))]
(dotimes [i (count xss)]
(let [xs (aget xss i)]
(.add pq (pair i (first xs)))
(aset xss i (next xs))))
((fn go []
(lazy-seq
(if-let [[i x] (.poll pq)]
(let [ys (aget xss i)]
(if-let [y (first ys)]
(do (aset xss i (next ys))
(.add pq (pair i y))))
(cons x (go)))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment