描述
给定 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