使用c语言中的strcmp函数对给定字符串数组进行排序的函数



我一直在尝试编写一个名为sort的函数,该函数将函数及其大小作为参数,并使用c中的冒泡排序对数组进行排序,但我的大多数时间都不起作用。下面是代码:

#include<stdio.h>
#include<string.h>
void print(char a[][10], int size);
void sort(char a[][10], int size);
int main(){
int n;
scanf("%d", &n);
char a[n][10];

int i;
for (i = 0; i < n; i++){
scanf("%s", a[i]);
}

print(a, n);
sort(a, n);
print(a, n);
}
void print(char a[][10], int size){
int i;
printf("n");
for(i = 0; i < size; i++){
printf("%s", a[i]);
printf("n");
}
}
void sort(char a[][10], int size){
int i, j;
char temp[10];

for(i = 0; i < size; i++){
for(j = 0; j < size - i - 1; j++){
if(strcmp(a[j], a[j + 1]) > 0)
strcpy(temp , a[j]);
strcpy(a[j] , a[j + 1]);
strcpy(a[j + 1], temp);     
}
}
}

期望输入:3 man car dog

期望输出:car dog man

结果:dog man man

我上面写的代码只在顺序相反的情况下有效(人狗车)。请帮助。

在代码片段中:

if(strcmp(a[j], a[j + 1]) > 0)
strcpy(temp , a[j]);
strcpy(a[j] , a[j + 1]);
strcpy(a[j + 1], temp);

条件后面缺少大括号。应该是:

if(strcmp(a[j], a[j + 1]) > 0) {
strcpy(temp , a[j]);
strcpy(a[j] , a[j + 1]);
strcpy(a[j + 1], temp);
}

最新更新