algorithmlanguage-agnosticsortingmergecode-golf

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


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.

For example:

input:  ((1, 4, 7), (2, 5, 8), (3, 6, 9))
output: (1, 2, 3, 4, 5, 6, 7, 8, 9)

input:  ((1, 10), (), (2, 5, 6, 7))
output: (1, 2, 5, 6, 7, 10)

Note: solutions which concatenate the input lists then use a language-provided sort function are not in-keeping with the spirit of golf, and will not be accepted:

sorted(sum(lists,[])) # cheating: out of bounds!

Apart from anything else, your algorithm should be (but doesn't have to be) a lot faster!

Clearly state the language, any foibles and the character count. Only include meaningful characters in the count, but feel free to add whitespace to the code for artistic / readability purposes.

To keep things tidy, suggest improvement in comments or by editing answers where appropriate, rather than creating a new answer for each "revision".

EDIT: if I was submitting this question again, I would expand on the "no language provided sort" rule to be "don't concatenate all the lists then sort the result". Existing entries which do concatenate-then-sort are actually very interesting and compact, so I won't retro-actively introduce a rule they break, but feel free to work to the more restrictive spec in new submissions.


Inspired by Combining two sorted lists in Python


Solution

  • Common Lisp already has a merge function for general sequences in the language standard, but it only works on two sequences. For multiple lists of numbers sorted ascendingly, it can be used in the following function (97 essential characters).

    (defun m (&rest s)
      (if (not (cdr s))
          (car s)
          (apply #'m
                 (cons (merge 'list (car s) (cadr s) #'<)
                       (cddr s))))) 

    edit: Revisiting after some time: this can be done in one line:

    (defun multi-merge (&rest lists)
      (reduce (lambda (a b) (merge 'list a b #'<)) lists))
    

    This has 79 essential characters with meaningful names, reducing those to a single letter, it comes out at 61:

    (defun m(&rest l)(reduce(lambda(a b)(merge 'list a b #'<))l))