字符串排序2 (对二维数组进行排序,储存在指针数组里)

13 篇文章 1 订阅
13 篇文章 0 订阅

1.主函数中定义一个二维字符数组s[5][MX], 然后输入n(n<=5)个字符串, 字符串最大长度为MX(MX=32);

2.编写函数sort1(), 对输入的字符串按字母序升序排序,返回排序结果;

3.编写函数sort2(), 对输入的字符串按字母序降序排序,返回排序结果;

4.主函数中调用sort1()和sort2(), 完成功能验证.

输入样例:

5
I want to learning english.
C programming is fun.
Nice to meet you.
See you.
Happy new year.

输出样例:

Ascending:
C programming is fun.
Happy new year.
I want to learning english.
Nice to meet you.
See you.
Descending:
See you.
Nice to meet you.
I want to learning english.
Happy new year.
C programming is fun.

 代码如下:

#include <stdio.h>
#include <string.h>
#define STR_LEN  (32+1)


void sort1(char s[][STR_LEN], int n, char *rlt[5])
{
    int i,j;
    char (*p)[STR_LEN] = s;

    for(i = 0; i < n - 1; i++)
    {
        rlt[i] = *(p + i);
        for(j = i + 1; j < n; j++)
        {//进行升序排序
            if(strcmp(*(p + i),*(p + j)) > 0)
            {
                char a[STR_LEN];
                strcpy(a,*(p + i));
                strcpy(*(p + i),*(p + j));
                strcpy(*(p + j),a);
                rlt[i] = *(p + i);//指针数组第i个元素指向*(p + i)
            }//if
        }//for
    }//for

    rlt[n - 1] = *(p + n - 1);

}//sort1

void sort2(char s[][STR_LEN], int n, char *rlt[5])
{
    int i,j;
    char (*p)[STR_LEN] = s;

    for(i = 0; i < n - 1; i++)
    {
        rlt[i] = *(p + i);
        for(j = i + 1; j < n; j++)
        {//进行降序排序
            if(strcmp(*(p + i),*(p + j)) < 0)
            {
                char a[STR_LEN];
                strcpy(a,*(p + i));
                strcpy(*(p + i),*(p + j));
                strcpy(*(p + j),a);
                rlt[i] = *(p + i);//指针数组第i个元素指向*(p + i)
            }//if
        }//for
    }//for

    rlt[n - 1] = *(p + n - 1);

}//sort2


int main()
{
    int i, n;
    char s[5][STR_LEN] = {0};
    char *rlt[5];

    scanf("%d\n", &n);

    for(i=0;i<n;i++)
    {
        gets(s[i]);
    }//for

    // 升序排序
    printf("Ascending:\n");
    sort1(s, n, rlt);

    for(i=0; i<n; i++)
    {
        puts(rlt[i]);
    }//for

    // 降序排序
    printf("Descending:\n");
    sort2(s, n, rlt);

    for(i=0; i<n; i++)
    {
        puts(rlt[i]);
    }//for
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值