冒泡排序混乱

Bubble Sorting Confusion

我正在尝试制作一个程序,该程序将读取包含单词的 .txt 文件,然后将这些单词按字母顺序放入另一个 .txt 文件中。我四处寻求帮助,人们一直说冒泡排序可以解决问题,但是 none 他们中的 none 非常有帮助或可以理解,我不知道如何将冒泡排序合并到我的代码中,因为如下:

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] << " ";
}

现在它所做的只是将原始 .txt 文件按原始顺序逐字打印到屏幕上(并在我完成后打印到文本文件中)。如何在此程序中加入冒泡排序以按字母顺序输入?

您正在从 'word' 中的 normalfile 中获取字符串。 在此之后,您可以尝试使用 sort 函数作为 sort(word.begin(),word.end())。不要忘记包含算法 header。现在,由于您的单词已排序,您可以将其文本放入按字母顺序排列的文件中。 希望对你有帮助。

如果你想使用冒泡排序,你应该在代码后添加:

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;
        }
    }

剩下的就是将所有单词按字母顺序排列;

for(j = 0; j < i; ++j){
    alphabetized << word[j];
}

就是这样。