c十个字符串冒泡排序
时间: 2024-06-08 10:04:02 浏览: 130
在C语言中,使用十个字符串(即字符数组)进行冒泡排序并不直接像整数或浮点数那样操作,因为字符串是不可比较的。不过,我们可以将字符串视为字符数组,然后按照字典序(ASCII值)对它们进行排序。这里是一个简单的冒泡排序算法示例,用于对包含字符数组的结构体(如`struct`)进行排序:
```c
#include <stdio.h>
#include <string.h>
typedef struct {
char str[10];
} StringItem;
void bubble_sort(StringItem arr[], int n) {
int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (strcmp(arr[j].str, arr[j+1].str) > 0) {
// 交换两个字符串
temp = arr[j].str;
arr[j].str = arr[j+1].str;
arr[j+1].str = temp;
}
}
}
}
int main() {
StringItem items[] = {"abc", "xyz", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yzw"};
int n = sizeof(items) / sizeof(items);
printf("Before sorting:\n");
for (int i = 0; i < n; i++) {
printf("%s ", items[i].str);
}
bubble_sort(items, n);
printf("\nAfter sorting:\n");
for (int i = 0; i < n; i++) {
printf("%s ", items[i].str);
}
return 0;
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)