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?
#include <iostream>
#include <fstream>
#include <vector>
usingnamespace 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.