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

anm*_*oo7 2 c arrays sorting string

问题

我已经制作了类似于其他在

https://beginnersbook.com/2015/02/c-program-to-sort-set-of-strings-in-alphabetical-order/

但是我制作的程序不起作用。我认为两者都是一样的,但我的程序给了我浪费的输出。

另外我想知道在其他程序中计数设置为 5 并且它应该从 0 开始需要 6 个输入但它只得到 5,如何?

我的程序

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

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;j<5;j++)
        if(strcmp(str[i],str[j])>0){
            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;

}
Run Code Online (Sandbox Code Playgroud)

Dút*_*has 11

使用qsort().

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

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 ] );
}
Run Code Online (Sandbox Code Playgroud)

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