2017-02-04 140 views
1

我们必须输入n个字符串,并按照长度和ascii值进行排序的升序排序。 请帮助.... 有一个样本测试案例: 没有琴弦5 奥马尔 苹果 香蕉 蚂蚁 猫使用ascii和字符串长度对字符串进行排序

,输出必须是: 蚂蚁猫奥马尔苹果香蕉

enter code here: 
#include<stdio.h> 
#include<string.h> 
int main() 
{ 
    int n,i,l,m,j; 
    char str[20][20],temp[20],temp2[20][20]; 
    printf("enter no of strings\n"); 
    scanf("%d",&n); 
// string is given as input 
    for(i=0; i<n; i++) 
    { 
     fflush(stdin); 
     scanf("%s",str[i]); 
     l=strlen(str[i]); 
     printf("len is %d\n",l); 
    } 
//sorting on the basis of length 
    for(i=0; i<=n; i++) 
     for(j=i+1; j<=n; j++) 
     { 
      if(strlen(str[i])>strlen(str[j])) 
      { 
       strcpy(temp,str[i]); 
       strcpy(str[i],str[j]); 
       strcpy(str[j],temp); 
      } 
     } 
//sorting on the basis of ascii values 
    for(i=0; i<n; i++) 
    { 
     if(l==m)// spcl condition 
     { 
      printf("\ncheck",l,m); 
      for(j=0; j<strlen(str[i]); j++) 
      { 
       if(strcmp(str[j][i],str[j][++i])>0) 
       { 
        strcpy(temp2[20],str[i]); 
        strcpy(str[i],str[++i]); 
        strcpy(str[++i],temp2[20]); 
       } 
      } 
     } 
     else// default condition 
     { 
      strcpy(temp2[20],str[i]); 
      strcpy(str[i],str[++i]); 
      strcpy(str[++i],temp2[20]); 
     } 
    } 
//display each string 
    printf("the strings are\n"); 
    for(i=0; i<n; i++) 
    { 
     printf("%s",str[i]); 
     printf("\n"); 
    } 

    return 0; 
} 

回答

0

够简单。

qsort采用用户定义的比较函数。所以先比较长度。如果它们相同,则调用strcmp按字母顺序进行比较。

如果您需要实现qsort,请首先使用相同的接口编写bubblesort以使其正常工作,然后使用更快的算法进行替换。

相关问题