Code golf: combining multiple sorted lists into a single sorted list

前端 未结 26 1950
余生分开走
余生分开走 2020-12-29 12:42

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.

26条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-29 12:46

    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:

    • my solution (Merge)
    • sorted(sum(lists, [])) (Built-in)
    • Deestan's solution which sorted in a different way (Re-implement)

    List merge performance

    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()
    • Deestan's solution is O(N**2) so it is excluded from the comparison (all other solutions are O(N) (for the input provided))

    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_
    

    Performance data Nmax=2**16 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.

提交回复
热议问题