图书馆新进一批图书,每本图书的名字均不超过 50 字符。编写一程序,将这些图书的名学按照由小到大的顺序排列。要求:排序通过函数进行,数据的输入输出及函数调用在主函数中进行。严格按照下列函数名和变量定义选行程序编写。 void sort(char book[][50], int n) {••••••} void main{} {char name[10][50];••••••}
时间: 2023-12-18 19:05:40 浏览: 20
好的,我可以帮你解答这个问题。下面是代码:
```c
#include <stdio.h>
#include <string.h>
void sort(char book[][50], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (strcmp(book[j], book[j + 1]) > 0) {
char temp[50];
strcpy(temp, book[j]);
strcpy(book[j], book[j + 1]);
strcpy(book[j + 1], temp);
}
}
}
}
int main() {
char name[10][50];
int n;
printf("请输入图书数量(不超过10本):");
scanf("%d", &n);
printf("请输入图书名称:\n");
for (int i = 0; i < n; i++) {
scanf("%s", name[i]);
}
sort(name, n);
printf("图书名称按照字典序排序后为:\n");
for (int i = 0; i < n; i++) {
printf("%s\n", name[i]);
}
return 0;
}
```
程序的思路是:先输入图书数量和名称,然后调用 `sort` 函数进行排序,最后输出排序后的结果。
`sort` 函数中使用了冒泡排序的思想,通过 `strcmp` 函数比较两个字符串的大小关系,如果前一个字符串大于后一个字符串,则交换它们的位置。
注意,在输入图书名称时使用 `%s` 格式化字符串,因为每本图书的名字长度不超过 50 字符。同时,在 `sort` 函数中也要使用 `strcpy` 函数,因为 `book[j]` 和 `book[j + 1]` 都是字符串数组,不能直接进行赋值操作。
希望对你有帮助!