7-30 字符串的冒泡排序 (20 分)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44720323/article/details/100968841
#include <stdio.h>
#include <string.h>

int main()
{
    int num,k;
    char s[101][11];
    char temp[11];
    int m=0;
    scanf("%d %d",&num,&k);
    for(int i=0;i<num;i++){
        scanf("%s",&s[i]);
    }
    for(int i=0;i<k;i++){
        for(int j=0;j<num-i-1;j++){
        	m=0;
        	//可以用strcmp代替下面用来比较字符串的大小
        	while(s[j][m] != '\0' && s[j+1][m] != '\0' &&(s[j][m] == s[j+1][m])){ 
        		m++;
        		if(s[j][m] > s[j+1][m]){
                strcpy(temp,s[j]);
                strcpy(s[j],s[j+1]);
                strcpy(s[j+1],temp);
                break;
            	}
			} 
			if(s[j][0] > s[j+1][0]){
                strcpy(temp,s[j]);
                strcpy(s[j],s[j+1]);
                strcpy(s[j+1],temp);
            	}
        }
    }
    for(int j=0;j<num;j++){
        printf("%s\n",s[j]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44720323/article/details/100968841