Implement an algorithm to merge an arbitrary number of sorted lists into one sorted list. The aim is to create the smallest working programme, in whatever language you like.
Python: 113 characters
def m(c,l):
try:
c += [l[min((m[0], i) for i,m in enumerate(l) if m)[1]].pop(0)]
return m(c,l)
except:
return c
# called as:
>>> m([], [[1,4], [2,6], [3,5]])
[1, 2, 3, 4, 5, 6]
EDIT: seeing as talk of performance has come up in a few places, I'll mention that I think this is pretty efficient implementation, especially as the lists grow. I ran three algorithms on 10 lists of sorted random numbers:
sorted(sum(lists, []))
(Built-in)EDIT2: (JFS)
The figure's labels:
merge_26
-- heapq.merge()
from Python 2.6 stdlib merge_alabaster
-- the above code (labeled Merge
on the above figure)sort_builtin
-- L = sum(lists,[]); L.sort()
Input data are [f(N) for _ in range(10)]
, where f()
is:
max_ = 2**31-1
def f(N):
L = random.sample(xrange(max_), n)
L.sort()
return L
f.__name__ = "sorted_random_%d" % max_
NOTE:
merge_alabaster()
doesn't work for N > 100
due to RuntimeError: "maximum recursion depth exceeded"
.
To get Python scripts that generated this figure, type:
$ git clone git://gist.github.com/51074.git
Conclusion: For reasonably large lists the built-in sort shows near linear behaviour and it is the fastest.