如何在C中按升序对字符串数组进行排序

问题

我已经制作了与其他类似的排序程序

C Program to Sort set of strings in alphabetical order

但我做的程序不起作用。 我认为两者都是一样的,但我的计划给了我废物输出。

另外我想知道其他程序计数设置为5例如它应该从0开始输入6但是它只获得5,如何?

我的计划

#include  #include  int main() { char str[4][10],temp[10]; int i,j; printf("Enter strings one by one : \n"); for(i=0;i<5;i++) scanf("%s",str[i]); for(i=0;i<5;i++) for(j=i+1;j0){ strcpy(temp,str[i]); strcpy(str[i],str[j]); strcpy(str[j],temp); } printf("\nSorted List : "); for(i=0;i<5;i++) printf("\n%s",str[i]); printf("\n\n"); return 0; } 

这不是答案,而是对您所指代码的一些批评:

 #include #include int main(){ int i,j,count; char str[25][25],temp[25]; puts("How many strings u are going to enter?: "); scanf("%d",&count); // (1) puts("Enter Strings one by one: "); for(i=0;i<=count;i++) // (2) gets(str[i]); for(i=0;i<=count;i++) for(j=i+1;j<=count;j++){ if(strcmp(str[i],str[j])>0){ strcpy(temp,str[i]); strcpy(str[i],str[j]); strcpy(str[j],temp); } } printf("Order of Sorted Strings:"); // (3) for(i=0;i<=count;i++) puts(str[i]); return 0; } 

批评:

(1) scanf("%d",&count); 将数字读入计数,然后返回。 它不消耗换行符(!)

(2)这个循环不打印任何东西,只是读取。 但是,如果你把

  for(i=0;i<=count;i++){ printf("%d:",i); gets(str[i]); } 

在它的位置,你会突然看到它要求名字0 ... 5,只是自动跳过0。 这是消耗断行的地方,它读取一个空字符串。 您也可以将其显示出来,如果不是将5放入初始问题,那么您需要放置5 anmoloo7

(3)在打印输出中,名称出现在标题Order of Sorted Strings下方。 但是printf中没有换行符。 问题是空字符串比任何其他字符串“更小”,因此它到达列表的前面,然后首先打印出来。 如果您在初始数字后面添加名称的“技巧”,输出将看起来不同,将有6个名称,其中一个直接附加到标题。

另外还有你可能从你的编译器得到的东西: gets是一个致命的函数,忘记它的存在并使用fgets与其他答案中出现的stdin。

它应该从0开始输入6但是它只得到5,怎么样?

这个循环

 for(i=0;i<5;i++) scanf("%s",str[i]); 

执行i为0,1,2,3,4所以它循环5次。

如果你想要6个循环呢

 for(i=0;i<=5;i++) ^ Notice 

要么

 for(i=0;i<6;i++) ^ Notice 

还要注意这一行

 char str[6][10],temp[10]; ^ Notice 

这样你可以保留6个字符串的内存

我有这个样本:

 #include  #include  void main() { char str[100],ch; int i,j,l; printf("\n\nSort a string array in ascending order :\n"); printf("--------------------------------------------\n"); printf("Input the string : "); fgets(str, sizeof str, stdin); l=strlen(str); /* sorting process */ for(i=1;istr[j+1]) { ch=str[j]; str[j] = str[j+1]; str[j+1]=ch; } printf("After sorting the string appears like : \n"); printf("%s\n\n",str); } 

使用qsort()

 #include  #include  #include  int pstrcmp( const void* a, const void* b ) { return strcmp( *(const char**)a, *(const char**)b ); } int main() { const char* xs[] = { "Korra", "Zhu Li", "Asami", "Mako", "Bolin", "Tenzin", "Varrick", }; const size_t N = sizeof(xs) / sizeof(xs[0]); puts( "(unsorted)" ); for (int n = 0; n < N; n++) puts( xs[ n ] ); // Do the thing! qsort( xs, N, sizeof(xs[0]), pstrcmp ); puts( "\n(sorted)" ); for (int n = 0; n < N; n++) puts( xs[ n ] ); } 

请不要使用冒泡排序。 在C中,您实际上不必在特殊需求之外编写自己的排序算法。