HJ14 字符串排序(数组指针+冒泡排序)

描述

给定 n 个字符串,请对 n 个字符串按照字典序排列。

数据范围: 1≤n≤1000 ,字符串长度满足 1≤len≤100

输入描述:

输入第一行为一个正整数n(1≤n≤1000),下面n行为n个字符串(字符串长度≤100),字符串中只含有大小写字母。

输出描述:

数据输出n行,输出结果为按照字典序排列的字符串。

示例1

输入:
9
cap
to
cat
card
two
too
up
boat
boot
输出:
boat
boot
cap
card
cat
to
too
two
up

实现

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define M_ARRAY_SIZE   (100 + 1)
void BubbleSort(char (*pBuf)[M_ARRAY_SIZE], int n)
{
    int flag;
    int i = 0, j = 0;
    char tmp[M_ARRAY_SIZE] = {0};

    for (i = 0; i < n - 1; i++) //共进行n-1次
    {
        flag = 1;
        for (j = 0; j < n - 1 - i; j++) // 每一次找出最大的放最后面
        {
            if (strcmp(pBuf[j], pBuf[j+1]) > 0)
            {
                memset(tmp, 0, sizeof(tmp));
                strcpy(tmp, pBuf[j]);
                strcpy(pBuf[j], pBuf[j+1]);
                strcpy(pBuf[j+1], tmp);
                flag = 0;
            }
        }
#if 0        
        printf("after sort i: %d. ", i);
        for (int m = 0; m < n; m++) {
            printf("%s ", pBuf[m]);
        }
        printf("\n");
#endif
        if (flag == 1) {
            printf("flag: %d, do not need sort\n", flag);
            break;
        }
    }
}

int main()
{
    int i, n = 0;
    char (*pBuf)[M_ARRAY_SIZE] = NULL;   // 数组指针
    
    scanf("%d", &n);
    pBuf = (char (*)[M_ARRAY_SIZE])malloc(n * M_ARRAY_SIZE * sizeof(char));
    if (pBuf == NULL) {
        printf("malloc fail\n");
        return -1;
    }
    memset(pBuf, 0, n * M_ARRAY_SIZE);
    for (i = 0; i < n; i++) {
        scanf("%s", pBuf + i);
    }
#if 0  
    printf("n: %d\n", n);
    for (i = 0; i < n; i++) {
        printf("%s ", pBuf + i);
    }
    printf("\n");
#endif    
    BubbleSort(pBuf, n);
    for (i = 0; i < n; i++) {
        printf("%s\n", pBuf + i);
    }
    return 0;
}

调试

orig: cap to cat card two too up boat boot
after sort i: 0. cap cat card to too two boat boot up 
after sort i: 1. cap card cat to too boat boot two up 
after sort i: 2. cap card cat to boat boot too two up 
after sort i: 3. cap card cat boat boot to too two up 
after sort i: 4. cap card boat boot cat to too two up 
after sort i: 5. cap boat boot card cat to too two up 
after sort i: 6. boat boot cap card cat to too two up 
after sort i: 7. boat boot cap card cat to too two up 
flag: 1, do not need sort
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

未停丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值