用指针数组对字符串排序
时间: 2024-03-03 11:44:32 浏览: 73
对于指针数组进行字符串排序,可以使用冒泡排序或快速排序算法。下面是两种排序算法的示例代码:
1. 冒泡排序:
```c
#include <stdio.h>
#include <string.h>
void bubbleSort(char* str[], int n) {
int i, j;
char* temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (strcmp(str[j], str[j+1]) > 0) {
temp = str[j];
str[j] = str[j+1];
str[j+1] = temp;
}
}
}
}
int main() {
char* str[] = { "beijing", "guangdong", "shanghai" };
int n = sizeof(str) / sizeof(str[0]);
bubbleSort(str, n);
printf("Sorted strings: ");
for (int i = 0; i < n; i++) {
printf("%s ", str[i]);
}
return 0;
}
```
2. 快速排序:
```c
#include <stdio.h>
#include <string.h>
void swap(char** a, char** b) {
char* temp = *a;
*a = *b;
*b = temp;
}
int partition(char* str[], int low, int high) {
char* pivot = str[high];
int i = low - 1;
for (int j = low; j <= high - 1; j++) {
if (strcmp(str[j], pivot) < 0) {
i++;
swap(&str[i], &str[j]);
}
}
swap(&str[i+1], &str[high]);
return (i + 1);
}
void quickSort(char* str[], int low, int high) {
if (low < high) {
int pi = partition(str, low, high);
quickSort(str, low, pi - 1);
quickSort(str, pi + 1, high);
}
}
int main() {
char* str[] = { "beijing", "guangdong", "shanghai" };
int n = sizeof(str) / sizeof(str[0]);
quickSort(str, 0, n - 1);
printf("Sorted strings: ");
for (int i = 0; i < n; i++) {
printf("%s ", str[i]);
}
return 0;
}
```
阅读全文