I'm trying to make a program that will read in a .txt file with words, and then put those words into another .txt file in alphabetical order. I've looked around for help and people keep saying that a bubble sort will do the trick, but none of them are very helpful or understandable and I don't know how to incorporate a bubble sort into my code, as follows:
ifstream normalfile;
ofstream alphabetized;
string word[250]
int i;
normalfile.open("/*filepath*/");
alphabetized.open("/*filepath*/");
if (!normalfile)
{
cout << "Normal File Error" << endl;
return 0;
}
if (!alphabetized)
{
cout << "Alphabetized File Error" << endl;
return 0;
}
for (i = 0; !normalfile.eof(); i++)
{
normalfile >> word[i];
cout << word[i] << " ";
}
Right now all it does is print out to the screen (and out to the text file when I finalize it) the original .txt file word for word in original order. How do I incorperate a bubble sort in this program to put in in alphabetical order?
If you want to use bubble sort you should add this after your code:
int j, k;
string temp;
for(j = 0; j < i; ++j) /*since the last for i stores the amount of
words you want to sort, so this for gets repeat i times */
for( k = 0; k < i - j; ++k){ /*here you go trought the array first
until words[i - 1], second until words[i - 2] and so on...,
this because at the end of each cicle the last element
is garantized to be already in order*/
if(words[k] > words[k + 1]){/*if the actual element words[k] is greather
than words[k + 1] swap their values*/
temp = words[k];
words[k] = words[k + 1];
words[k + 1] = temp;
}
}
All is left is to put all the words in alphabetized;
for(j = 0; j < i; ++j){
alphabetized << word[j];
}
That´s it.