Click here to Skip to main content
15,890,506 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
How do I sort a text file I/O in alphabetical order?
Posted
Updated 6-Dec-09 9:50am
v2

1 solution

If the text file is small, you can read each line into memory, apply a sort on the lines, then write them all back to the same file in their sorted order.

If a large text file, you can sort the lines in the text file without loading more than 2 into memory at once. Start with the first line, read it in, and call this the "current" line. Next, compare it to the second line in the file. If they are not in the correct order, swap them, then use the previous line in the text file as the "current" line (if you reach the beginning of the file, just reapply the same algorithm starting from the first line in the file). If the lines match, move on to the next line in the file and make that the "current" line. Continue this procedure until you've reached the end of the file.

There are faster ways of sorting text files, but that is the simplest way I could describe it to you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900