(C语言题目)输入多个城市名,按升序顺序输出。想问一下具体步骤,且最好每个步骤都写明原因,谢谢!

2024-12-22 21:36:10
推荐回答(2个)
回答1:

按照城市名称的拼音字母的英文ASCII码顺序排序,升序是指从a到z,比如海南(hainan)应该排在河南(henan)之前。

/*

排序前:
One-1 Two-2 Three-3 Four-4 Five-5 Six-6 Seven-7 Eight-8 Nine-9 Ten-10

排序后:
Eight-8 Five-5 Four-4 Nine-9 One-1 Seven-7 Six-6 Ten-10 Three-3 Two-2
Press any key to continue

*/

#include 
#include
#define N 10
void mystrcpy(char *destStr,char *sourceStr) {
while(*destStr++ = *sourceStr++);
}
void mysort(char s[][N]) {
unsigned i,j,k;
char t[100];
for(i = 0;i < N - 1;i++) {
k = i;
for(j = i + 1;j < N;j++)
if(strcmp(s[k],s[j]) > 0) k = j;
if(k != i) {
mystrcpy(t,s[i]);
mystrcpy(s[i],s[k]);
mystrcpy(s[k],t);
}
}
}
int main() {
unsigned int i;
char s[][N] = {"One-1","Two-2","Three-3","Four-4","Five-5","Six-6","Seven-7","Eight-8","Nine-9","Ten-10"};
printf("排序前:\n");
for(i = 0;i < N;i++) printf("%s ",s[i]); printf("\n");
mysort(s);
printf("\n排序后:\n"); for(i = 0;i < N;i++) printf("%s ",s[i]);
printf("\n");
return 0;
}

回答2:

你用strcmp比较一下就知道了 首先是比较首位的字母