PTA 英文单词排序 为什么我的代码过不了

本题要求编写程序,输入若干英文单词,对这些单词按长度从小到大排序后输出。如果长度相同,按照输入的顺序不变。

输入格式:
输入为若干英文单词,每行一个,以#作为输入结束标志。其中英文单词总数不超过20个,英文单词为长度小于10的仅由小写英文字母组成的字符串。

输出格式:
输出为排序后的结果,每个单词后面都额外输出一个空格。

输入样例:

blue
red
yellow
green
purple
#

输出样例:

red blue green yellow purple 

我的代码

#include <bits/stdc++.h>
#define LL long long
using namespace std;
bool cmp(string a,string b)
{
    return a.length() < b.length();
}
int main()
{
    string a[50];
    int n = 0;
    while(cin >> a[n])
    {
        if(a[n][0] == '#')
        {
            break;
        }
        n++;
    }
    sort(a,a+n,cmp);
    for(int i = 0;i < n;i++)
        cout << a[i] << " ";
    return 0;
}

img

sort排序不稳定,对于相等的情况不能保证保持原顺序。


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