2016-03-05 115 views
-3

我正在嘗試製作一個程序,它將用單詞讀入.txt文件,然後按字母順序將這些單詞放入另一個.txt文件中。我已經四處尋求幫助,人們總是說泡泡排序可以做到這一點,但它們都不是非常有幫助或可以理解的,我不知道如何將泡泡排序整合到我的代碼中,如下所示:冒泡排序混淆

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文件字。我如何在這個程序中使用冒泡排序來按字母順序排列?

+0

這段代碼中沒有任何地方排序......你只是問「你怎麼寫一個冒泡排序」? – Barry

+0

是的,我基本上是問如何在這段代碼中使用冒泡排序。 – Herides

+0

@Herides您在此代碼中使用冒泡排序的方式與您在任何代碼中使用冒泡排序的方式相同。這段代碼沒有什麼特別之處,需要使用冒泡排序的特殊方式。 –

回答

0

如果你想使用冒泡排序,你應該代碼後補充一點:

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

就是這樣。

+0

非常感謝你,這正是我所需要的,並且我有更好的理解。非常感謝你。 – Herides

+0

歡迎您:) –

0

您正在從'word'中的normalfile中取得字符串。 之後你可以嘗試使用排序函數sort(word.begin(),word.end())。不要忘記包含算法頭。現在,由於您的單詞已排序,您可以將其文本置於按字母順序排列的文件中。 希望它有幫助。

+0

std :: sort不是冒泡排序。 –