sort函数 南华新生训练2017-字符串排序

描述
给出n(n<300)个字符串:S1,S2……Sn;每个字符串的长度不超过100,将这n个字符串按字典序升序输出;

输入
单组输入;
第一行输入一个整数n(n<300);
2到n+1行输入n个字符串Si;|Si|<100;

输出
按字典序升序输出n行。

样例输入1 复制
4
a
c
d
b
样例输出1
a
b
c
d
样例输入2 复制
4
aabcd
daeda
ddeww
gbeew
样例输出2
aabcd
daeda
ddeww
gbeew

我的思路:

就像数据大小排序中的插入排序一样,每次输入一个字符串就判断他的大小,然后把它插入相应的位置。

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define maxn 105
char s[305][maxn];
int main()
{
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; i++)
    {
        scanf("%s", s[i]);
        for(int j = 0; j < i; j++)
        {
            for(int q = 0; ; q++)
            {
                if(s[j][q] > s[i][q] || s[i][q] == '\0')
                {
                    char l[maxn];
                    strcpy(l, s[i]);
                    for(int p = i; p > j; p--)
                    {
                        strcpy(s[p], s[p - 1]);
                    }
                    strcpy(s[j], l);
                    break;
                }
                if(s[j][q] == s[i][q])continue;
                if(s[j][q] < s[i][q] || s[j][q] == '\0')break;
            }
        }
    }
    for(int i = 0; i < n; i++)
        printf("%s\n", s[i]);
    return 0;
}
哆啦A梦的思路:

直接用sort函数即可按照字典序排列(我一直以为sort函数只能排列数值的大小)
需要包含头文件string和algorithm

#include <cstdio>  
#include <algorithm>  
#include <cmath>  
#include <iostream>  
#include <map>   
#include <queue>  
#include <cstdlib>  
#include <cstring>  
#include <string>  
#include <ctime>  
#include <vector>  

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef long double ldb;

const ll MOD = 1000000009;
const int INF = 0x3f3f3f3f;
const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
const db PI = acos(-1);
const db ERR = 1e-8;

int main(){
    int n;
    cin>>n;
    string s[303];
    for(int i=0;i<n;i++){
        cin>>s[i];
    }
    sort(s,s+n);
    for(int i=0;i<n;i++){
        cout<<s[i]<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值