習題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