gpt4 book ai didi

c - 字符串数组排序 C

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:22:07 28 4
gpt4 key购买 nike

我一直在尝试让这个程序按列索引对二维字符串数组进行排序。

我像这样初始化了这个二维数组:

char *str[ROWS][COLS] = {{"Russia", "Boxing", "Mens", "Gold"},
{"America", "Cycling", "Mens", "Gold"},
{"New Zealand", "Swimming", "Womens", "Silver"},
{"India", "Badminton", "Mens", "Bronze"}};

如果我想按第一列(国家名称)对这个数组进行排序,那么它将看起来像这样:

char *str[ROWS][COLS] = {{"America", "Cycling", "Mens", "Gold"}, 
{"India", "Badminton", "Mens", "Bronze"}};
{"New Zealand", "Swimming", "Womens", "Silver"},
{"Russia", "Boxing", "Mens", "Gold"}};

这是我到目前为止所做的,几乎是正确的,除了排序方法。我在实现时遇到了麻烦。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ROWS 4
#define COLS 4

void print_array(char *str[][COLS]);
void sort_array(char *str[][COLS], int nrows, int col);

int
main(void) {
char *str[ROWS][COLS] = {{"Russia", "Boxing", "Mens", "Gold"},
{"America", "Cycling", "Mens", "Gold"},
{"New Zealand", "Swimming", "Womens", "Silver"},
{"India", "Badminton", "Mens", "Bronze"}};
int col;

/* array before sorting */
printf("Before: \n");
print_array(str);

/*choosing column index to sort by*/
printf("\nChoose which column index you wish to sort by: ");
if (scanf("%d", &col) != 1) {
printf("Invalid input\n");
exit(EXIT_FAILURE);
}

sort_array(str, ROWS, col);

/* array after sorting */
printf("\nAfter: \n");
print_array(str);

return 0;
}

void
print_array(char *str[][COLS]) {
int i, j;

for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
printf("%s ", str[i][j]);
}
printf("\n");
}
}

/*function used for sorting the array */
void
sort_array(char *str[][COLS], int nrows, int col) {
int i, j;
char *temp;

for (i = 0; i < nrows; i++) {
for (j = i; j < nrows; j++) {
if(strcmp(str[i][col], str[j][col]) > 0) {
temp = str[i][col];
str[i][col] = str[j][col];
str[j][col] = temp;
}
}
}
}

我遇到的问题是我的排序算法不是交换行,而是交换该列中的字符串。我还尝试使用 insertion sort 算法,但我不确定如何使用二维字符串数组来实现它。

任何帮助将不胜感激:)

最佳答案

从 C11 开始,您可以按如下方式进行:

int compare_col(const void *a, const void *b, void *ctx) {
int col = *(int*)ctx;
return strcmp(((char**)a)[col], ((char**)b)[col]);
}

/*function used for sorting the array */
void sort_array(char *str[][COLS], int nrows, int col) {
qsort_s(str, nrows, sizeof(char*)*COLS, compare_col, &col);
}

关于c - 字符串数组排序 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39315932/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com