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
}