I assume that by citing merge sort, you are using native sort -- it will certainly have a smaller footprint than a homebrew solution. If you can't do it all in memory, have you considering using the divide and conquer algorithm that underlies merge sort and start by breaking the file into chunks, interleaving the final rounds with explicit file read/writes? As well, you may consider loading the data into an actual database for handling it. See Sorting data that don't fit in memory.
in reply to "Out of memory" problem
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.