习题8-7 字符串排序(用三种排序方法求解)


前言

用到排序算法的比较字符串题目

正文

题目:

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

输入格式:

输入为由空格分隔的5个非空字符串,每个字符串不包括空格、制表符、换行符等空白字符,长度小于80。

输出格式:

按照以下格式输出排序后的结果:
After sorted:
每行一个字符串

输入样例:

red yellow blue green white

输出样例:

After sorted:
blue
green
red
white
yellow

代码一(冒泡排序)

#include<stdio.h>
#include<string.h>
#define M 5
#define N 80
int main()
{
    char str[M][N],tmp[N];
    int i,j,pos;
    for(i=0;i<M;i++){
    scanf("%s",&str[i]);
    }
    /*冒泡排序*/
    for(i=0;i<M;i++){
        for(j=1;j<M;j++){
            if(strcmp(str[j],str[j-1])<0){//strcmp逐字比较
                strcpy(tmp,str[j-1]);//strcpy复制字符串
                strcpy(str[j-1],str[j]);
                strcpy(str[j],tmp);
            }
        }
    }
    printf("After sorted:\n");
    for(i=0;i<M;i++)
      printf("%s\n",str[i]);
    }
    return 0;
 } 

代码二(选择排序)

#include<stdio.h>
#include<string.h>
#define M 5
#define N 80
int main()
{
    char str[M][N],tmp[N];
    int i,j,pos;
    for(i=0;i<M;i++){
    scanf("%s",&str[i]);
    }
    /*选择排序*/
    for(i=0;i<M;i++){
    	pos=i;
    	for(j=i+1;j<M;j++){
    		if(strcmp(str[j],str[pos])<0){
    			pos=j;
			}
		}
		    strcpy(tmp,str[pos]);
			strcpy(str[pos],str[i]);
			strcpy(str[i],tmp);
	}
    printf("After sorted:\n");
    for(i=0;i<M;i++){
        printf("%s\n",str[i]);
    }
    return 0;
 } 

代码三(插入排序)

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

#define M 5
#define N 80
int main()
{
    char str[M][N],tmp[N];
    int i,j,pos,f;
    for(i=0;i<M;i++){
    scanf("%s",&str[i]);
    }
    /*插入排序*/
	for(i=1;i<M;i++){
		if(strcmp(str[i],str[i-1])<0){
			strcpy(tmp,str[i]);
			f=i;
		for(;f>=1&&strcmp(tmp,str[f-1])<0;f--){
			 strcpy(str[f],str[f-1]);
		   } 
		     strcpy(str[f],tmp);
        }
	} 
    printf("After sorted:\n");
    for(i=0;i<M;i++){
        printf("%s\n",str[i]);
    }
    return 0;
 } 

关于排序算法:排序算法浅解


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM