

K-way merge - Python way - mmihaljevic
http://melitamihaljevic.blogspot.com/2012/12/k-way-merge-python-way.html

======
cypherpunks01
Re-sorting with sorted() in #2 defeats the purpose of the k-way merge, you may
as well just materialize all the lists and sort them.

I didn't know about heapq.merge before, that seems like an efficient way to
go. Usually when I do k-way merges it's over a data stream, so I almost always
want an iterator.

~~~
mmihaljevic
you are right about sorted() but I was thinking it could be useful if you
don't have sorted arrays but need similar functionality and arrays are not too
big so you don't need an iterator but I was really amazed with heapq.merge()

I appreciate your comment

~~~
tantalor
> if you don't have sorted arrays

In this case certainly you should sort the multiple smaller arrays (in
parallel), not the merged one.

------
andrewcooke

        >>> from heapq import merge
        >>> def kmerge(*lists):
        ...   return merge(*map(sorted, lists))
        ... 
        >>> list(kmerge([1,2,3],[6,5,4],[2,2]))
        [1, 2, 2, 2, 3, 4, 5, 6]

