c语言数组n个字符串排序
时间: 2023-11-24 16:50:23 浏览: 131
字符串排序算法比较(C语言)
以下是两种C语言对n个字符串进行排序的例子:
1. 冒泡排序法
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int n, i, j;
char **str, s[100];
printf("请输入n:");
scanf("%d", &n);
getchar();
str = (char**)malloc(sizeof(char*) * n);
for (i = 0; i < n; i++) {
str[i] = (char*)malloc(sizeof(char) * 100);
scanf("%s", str[i]);
}
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (strcmp(str[j], str[j + 1]) > 0) {
strcpy(s, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1], s);
}
}
}
printf("排序后的字符串为:\n");
for (i = 0; i < n; i++) {
printf("%s\n", str[i]);
}
return 0;
}
```
2. 快速排序法
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void quick_sort(char **str, int left, int right) {
if (left >= right) {
return;
}
int i = left, j = right;
char *pivot = str[left];
while (i < j) {
while (i < j && strcmp(str[j], pivot) >= 0) {
j--;
}
str[i] = str[j];
while (i < j && strcmp(str[i], pivot) <= 0) {
i++;
}
str[j] = str[i];
}
str[i] = pivot;
quick_sort(str, left, i - 1);
quick_sort(str, i + 1, right);
}
int main() {
int n, i;
char **str;
printf("请输入n:");
scanf("%d", &n);
getchar();
str = (char**)malloc(sizeof(char*) * n);
for (i = 0; i < n; i++) {
str[i] = (char*)malloc(sizeof(char) * 100);
scanf("%s", str[i]);
}
quick_sort(str, 0, n - 1);
printf("排序后的字符串为:\n");
for (i = 0; i < n; i++) {
printf("%s\n", str[i]);
}
return 0;
}
```
阅读全文