C语言中字符串数组如何排序
时间: 2024-09-30 09:06:05 浏览: 48
在C语言中,直接对字符串数组进行排序通常比较复杂,因为标准库并没有提供内置的函数可以直接完成字符串数组的排序。但是,可以借助一些常见的算法,如冒泡排序、选择排序、插入排序、快速排序或归并排序等。这里以简单的冒泡排序为例来说明:
```c
#include <stdio.h>
#include <string.h>
// 冒泡排序函数
void bubbleSort(char strArray[], int n) {
for (int i = 0; i < n - 1; i++) { // 遍历数组
for (int j = 0; j < n - 1 - i; j++) { // 每轮遍历减少一个元素
if (strcmp(strArray[j], strArray[j + 1]) > 0) { // 如果当前元素大于下一个元素
char temp[100]; // 创建临时存储空间
strcpy(temp, strArray[j]); // 备份当前元素
strcpy(strArray[j], strArray[j + 1]); // 将下一个元素移动到前面
strcpy(strArray[j + 1], temp); // 将备份的元素放回原位置
}
}
}
}
int main() {
char strArray[] = {"banana", "apple", "orange", "grape"};
int n = sizeof(strArray) / sizeof(strArray[0]);
printf("Original array: ");
for (int i = 0; i < n; i++) {
printf("%s ", strArray[i]);
}
bubbleSort(strArray, n);
printf("\nSorted array: ");
for (int i = 0; i < n; i++) {
printf("%s ", strArray[i]);
}
return 0;
}
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![md](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)