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