I would do this in two steps:

1) read the input file line by line and create temporary files for each ID
2) then process each of those files, by reading the data into memory into a sorted container, e.g QMap, then writing that into the target file

Cheers,
_