sorting numbers in a file

i know how to sort numbers when a user inputs a constant set of numbers (example: cout<<"enter 10 numbers"; cin 10 numbers and then sorts them) but how do you sort an entire file that has an unknown amount of numbers?
There's not much difference. You can use eof()

http://www.cplusplus.com/reference/iostream/ios/eof/

in order to determine the end of the file


You might also use vector

http://www.cplusplus.com/reference/stl/vector/

because it dynamically resizes

In the most easiest case you might have something like this
1
2
3
4
5
6
7
8
std::fstream fi;
...
std::vector<int> vi;
int value;
while(fi >> value) // As long as the stream is ok (this includes eof)
{
  vi.push_back(value);
}
The easy way would be to read them into the vector, then sort them. Then rewrite the file with sorted values.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main ()
{
 ifstream fin;
 ofstream fout;
 fin.open("read.txt");
vector<int> vi;
int value;

while(fin >> value) // As long as the stream is ok (this includes eof)
{
  vi.push_back(value);
}
fin.close();
fout.open("read.txt");


   int i, j, first, temp;
      int numLength = vi.size();
      for (i= numLength - 1; i > 0; i--)
     {
           first = 0;                 // initialize to subscript of first element
           for (j=1; j<=i; j++)   // locate smallest between positions 1 and i.
          {
                 if (vi[j] > vi[first])
                 first = j;
          }
         temp = vi[first];   // Swap smallest found with element in position i.
         vi[first] = vi[i];
         vi[i] = temp;
     }

for(int i = 0 ; i<vi.size();i++)
{
	fout<<vi[i]<<" ";

}
fout.close();

return 0;
}
If the file is too big to hold into memory, then you would need to be creative. I don't know the proper way to go about it, or even a good way, but I can guess a way that might work.

You can read the file to see how many numbers there are, but if it's a big file, that's a lot of wasted time. So, I would just start sorting from the beginning. Take a couple thousand numbers, sort them however you like. Subzero says use a vector. Since vectors were made for this kind of stuff, I would use them, too. So take 10k numbers, sort them, put back into file, or different file. Read next batch, continue until end of file. This sorts them all according to batches of 10k numbers. Next, you'll have to think up a storm of an algorithm that can combine the batches to get all the numbers sorted.

Since numbers go on for infinity, this would be a very difficult task to do. But it's been done. You could probably find a program and some open source that does it.
Topic archived. No new replies allowed.