Suppose that we can't hold all files' contents in memory at the same time (let's say we can hold only two numbers from each file).

I heard that I can use some kind of R-way merge sort in this case but I don't understand how can I actually do it.

As you see, the first iteration will give us the following sorted sequence:

1 1 1 2 3 4

, so we flush it to the output file. However, we will get 1 again (from the 3.txt file) on the next iteration, so the whole resulting sequence is wrong!

网友答案:

Start by filling as many variables as you have files, one variable attached to one file. At each step find the lowest value of the three variables, and flush it to the output while filling it again from the same file.

I heard that I can use some kind of R-way merge sort in this case but I don't understand how can I actually do it.

N-way merges are quite easy to explain. You open all the files, get the first element from each and put them into a heap.
The algorithm then proceeds by getting the smallest element from the heap (pop), writing it to your output buffer and then read the next element from the file this item originated from. Repeat until all files are empty.