PTA习题 字符串排序

题目:本题要求编写程序,读入5个字符串,按由小到大的顺序输出。
题目详情
源码:

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

int main(void)
{
    char *str[5],temp[80],*t;
    int i = 0,j,index;
    
    for(i = 0;i < 5;i++)
    {
    	scanf("%s",temp); 
    	str[i] = (char *)malloc((strlen(temp) + 1) * sizeof(char));
//    	str[i] = (char *)malloc(80 * sizeof(char));		//注释掉的源码对应了另一种方法,但一定要保证字符串的长度相同,故统一定为80 
		strcpy(str[i],temp);	
	}													//采用动态分配内存的方法来处理多个字符串的输入问题 
    
    for(i = 0;i < 4;i++)
    {
        index = i;
        for(j = i + 1;j < 5;j++)
        {
            if(strcmp(str[j],str[index]) < 0)
                index = j;
        }
        t = str[i];
        str[i] = str[index];
        str[index] = t;							//通过变换指针的方式实现重新排序 
//		strcpy(temp,str[i]);
//      strcpy(str[i],str[index]);
//      strcpy(str[index],temp);				//通过拷贝字符串的方式实现重新排序 
    }											//选择排序法 
    
    printf("After sorted:\n");
    for(i = 0;i < 5;i++)
    {
    	printf("%s\n",str[i]);
    	free(str[i]);   	
	}

    return 0;
}

结果展示


版权声明:本文为yjwjwjw原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。