/*
26.在主程序中输入10个字符串,调用sort函数进行冒泡排序,然后在主函数中输出排序结果,
其中字符串长度不超过20,字符串排序方式(按字母序递增用1表示,按字母序递减用О表示)和待排序的字符串由参数传递给sort 函数。
要求自行设计 sort 函数,在主函数中,输入、输出应有相应提示。
*/
/*
boy abandon effert cook deadline finish idle jk good high
*/
#include <stdio.h>
#include <string.h>
#define M 10
#define N 21//末尾有个\0
void swap(char* s1, char* s2);
void sort(char str[M][N], int method);
int main() {
int i, method;
char str[M][N];
printf("输入10个字符串:\n");
for (i = 0; i < M; ++i) {
scanf("%s", str[i]);
}
printf("选择排序方式:1表示递增,0表示递减:");
scanf("%d", &method);
sort(str, method);
for (i = 0; i < M; ++i) {
puts(str[i]);
}
return 0;
}
void swap(char* s1, char* s2) {
char t[20];
strcpy(t, s1);
strcpy(s1, s2);
strcpy(s2, t);
}
void sort(char str[M][N], int method) {
int i, j;
for (i = 0; i < M - 1; ++i) {
for (j = 0; j < M - i - 1; ++j) {
if (method == 1 && strcmp(str[j], str[j + 1]) > 0) {
swap(str[j], str[j + 1]);
}
else if (method == 0 && strcmp(str[j], str[j + 1]) < 0) {
swap(str[j], str[j + 1]);
}
}
}
}
2019年26.在主程序中输入10个字符串,调用sort函数进行冒泡排序,然后在主函数中输出排序结果,其中字符串长度不超过20,字符串排序方式(按字母序递增用1表示,按字母序递减用О表示
于 2023-11-29 16:03:20 首次发布