改善代码 #include <stdio.h> #include <string.h> int main() { int swap(int *a,int *b); int numb; printf("How many strings you are going to enter?: \n"); scanf("%d",&numb); printf("\n\n\n"); int index[numb]; for(int i = 0; i < numb; i++) { index[i]=i; } char str[numb][30]; printf("Enter Strings One by One: \n"); for(int i = 0; i < numb; i++) { scanf("%s", str[i]); } for(int i = 0; i < numb-1; i++) { for(int j = i+1; j < numb; j++) { int inj = strcmp(str[index[i]], str[index[j]]); if(inj > 0) { swap(index[i],index[j]); } } } printf("Order of Sorted Strings: \n"); for(int i = 0; i < numb; i++) { printf("%s\n", str[index[i]]); } return 0; } int swap(int *a,int *b) { int mid = *b; *b = *a ; *a = mid; }
时间: 2024-04-28 15:19:05 浏览: 145
下面是改善后的代码,主要是优化了变量名和函数名,增加了注释,代码风格更加清晰易懂:
#include <stdio.h>
#include <string.h>
void swap(int *a, int *b); // 函数声明
int main() {
int num_strings; // 字符串数量
printf("How many strings you are going to enter?:\n");
scanf("%d", &num_strings);
int indices[num_strings]; // 索引数组
for (int i = 0; i < num_strings; i++) {
indices[i] = i;
}
char strings[num_strings][30]; // 字符串数组
printf("Enter Strings One by One:\n");
for (int i = 0; i < num_strings; i++) {
scanf("%s", strings[i]);
}
// 冒泡排序
for (int i = 0; i < num_strings - 1; i++) {
for (int j = i + 1; j < num_strings; j++) {
int cmp_result = strcmp(strings[indices[i]], strings[indices[j]]);
if (cmp_result > 0) {
swap(&indices[i], &indices[j]); // 交换索引
}
}
}
printf("Order of Sorted Strings:\n");
for (int i = 0; i < num_strings; i++) {
printf("%s\n", strings[indices[i]]);
}
return 0;
}
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
阅读全文