7-5 英文單詞排序 (25分)
本題要求編寫程序,輸入若干英文單詞,對這些單詞按長度從小到大排序後輸出。如果長度相同,按照輸入的順序不變。
輸入格式:
輸入爲若干英文單詞,每行一個,以#作爲輸入結束標誌。其中英文單詞總數不超過20個,英文單詞爲長度小於10的僅由小寫英文字母組成的字符串。
輸出格式:
輸出爲排序後的結果,每個單詞後面都額外輸出一個空格。
輸入樣例:
blue
red
yellow
green
purple
#
輸出樣例:
red blue green yellow purple
思路:
第一想法就是用string類型的vector,然後直接sort就完事。。。
#include <bits/stdc++.h>
using namespace std;
bool cmp(string s1,string s2)
{
return s1.size()<s2.size();
}
int main() {
vector<string>a;
string s;
while(1)
{
cin>>s;
if(s=="#")break;
a.push_back(s);
}
if (a.empty())cout<<endl;
sort(a.begin(),a.end(),cmp);
for (const auto & i : a) {
cout<<i<<" ";
}
return 0;
}
but。。。研究了半天也沒過去,查了一會才找到原因:
sort排序不穩定,對於相等的情況不能保證保持原順序。
所以冒泡排序,繼而AC
AC代碼:
#include <bits/stdc++.h>
using namespace std;
string s[21];
int main() {
string a;
int h=0;
while (1)
{
cin>>a;
if(a=="#")break;
s[h]=a;
h++;
}
int c=h;
while(c--)
{
for (int j = 1; j < h; ++j) {
if(s[j-1].length()>s[j].length())
swap(s[j],s[j-1]);
}
}
for (int i = 0; i < h; ++i) {
cout<<s[i]<<" ";
}
return 0;
}