Created
May 1, 2012 03:28
-
-
Save michalmarczyk/2564705 to your computer and use it in GitHub Desktop.
Multiway merge of sorted sequences
This file contains hidden or 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 [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