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.
GNU system scripting (I guess that's cheating, but it is nice to know too).
sort -m file1 file2 file3 ...
VB.NET (2008) 185 chars
Accepts List(Of List(Of Byte))
Function s(i)
s=New List(Of Byte)
Dim m,c
Dim N=Nothing
Do
m=N
For Each l In i:
If l.Count AndAlso(l(0)<m Or m=N)Then m=l(0):c=l
Next
If m<>N Then s.Add(m):c.Remove(m)
Loop Until m=N
End Function
Perl: 22 characters, including two significant whitespace characters.
sub a{sort map{@$_}@_}
Only builtins here. See? ;)
Call like so:
my @sorted = a([1, 2, 3], [5, 6, 89], [13, -1, 3]);
print "@sorted" # prints -1, 1, 1, 2, 3, 3, 5, 6, 89
Honestly, denying language features (note: not libraries...) seems kind-of counter the point. Shortest code to implement in a language should include buildins/language features. Of course, if you import a module, you should count that code against your solution.
Edit: removed unnecessary {}'s around the $_.
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))
OCaml in 42 characters:
let f=List.fold_left(List.merge compare)[]
I think I should get extra credit for 42 exactly?
(all other solutions are O(N) (for the input provided))
If we let N be the number of elements in the output and k the number of input lists, then you can't do faster than O(N log k) -- suppose that each list was only a single element, and you'd have faster-than-O(N log N) comparison-based sorting.
Those I've looked at look more like they're O(N*k).
You can fairly easily get down to O(N log k) time: just put the lists in a heap. This is one of the ways to do I/O-efficient sorting (you can generalize quicksort and heaps/heapsort as well).
[no code, just commentary]