我想基于numbers_column3
值以升序打印多个不同类型的数组。我有两个指针数组和一个浮点数组。我希望它们像第一行的a1,a2和a3的excel文档一样保持分组。每列有三个数组。我显示的代码只是一个简单的示例。目前,我的数组中大约有2万个值。有没有办法避免典型的气泡排序?那将需要大量的malloc和strcpy操作。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char **argv)
{
char *q6_tag_strings_line_column1[2000] = {0};
char *q6_nationality_strings_line_column2[2000] = {0};
float numbers_column3[2000] = {0};
q6_tag_strings_line_column1[0] =
malloc(strlen("echo")+1);
strcpy(q6_tag_strings_line_column1[0],
"echo");
q6_nationality_strings_line_column2[0] =
malloc(strlen("hi")+1);
strcpy(q6_nationality_strings_line_column2[0],
"hi");
numbers_column3[0] = 5;
q6_tag_strings_line_column1[1] =
malloc(strlen("how")+1);
strcpy(q6_tag_strings_line_column1[1],
"how");
q6_nationality_strings_line_column2[1] =
malloc(strlen("are")+1);
strcpy(q6_nationality_strings_line_column2[1],
"are");
numbers_column3[1] = 7;
q6_tag_strings_line_column1[2] =
malloc(strlen("you")+1);
strcpy(q6_tag_strings_line_column1[2],
"you");
q6_nationality_strings_line_column2[2] =
malloc(strlen("what")+1);
strcpy(q6_nationality_strings_line_column2[2],
"what");
numbers_column3[1] = 4;
return 0;
}
预期结果是
you what 4
echo hi 5
how are 7
最佳答案
如果三个数组的元素在语义上耦合,那么为什么不创建带有struct
,tag
和nationality
字段的number
。这使数据元素之间的连接更加明确,并允许使用标准库qsort()
函数创建并排序此类结构的数组。这是一个示例程序:
#include <stdio.h>
#include <stdlib.h>
struct Data {
char *tag;
char *nationality;
float number;
};
int compare_Data(const void *a, const void *b);
int main(void)
{
struct Data my_data[] = {
{ .tag = "North America",
.nationality = "Canadian",
.number = 3.3 },
{ .tag = "South America",
.nationality = "Brazilian",
.number = 5.5 },
{ .tag = "Asia",
.nationality = "Japanese",
.number = 1.1 },
};
puts("Before sorting:");
for (size_t i = 0; i < sizeof my_data / sizeof *my_data; i++) {
printf("Number: %f\n"
"Nationality: %s\n"
"Tag: %s\n",
my_data[i].number,
my_data[i].nationality,
my_data[i].tag);
putchar('\n');
}
qsort(my_data,
sizeof my_data / sizeof *my_data,
sizeof *my_data,
compare_Data);
puts("After sorting:");
for (size_t i = 0; i < sizeof my_data / sizeof *my_data; i++) {
printf("Number: %f\n"
"Nationality: %s\n"
"Tag: %s\n",
my_data[i].number,
my_data[i].nationality,
my_data[i].tag);
putchar('\n');
}
return 0;
}
int compare_Data(const void *a, const void *b)
{
const struct Data *da = (const struct Data *) a;
const struct Data *db = (const struct Data *) b;
return (da->number > db->number) - (da->number < db->number);
}
程序输出:
Before sorting:
Number: 3.300000
Nationality: Canadian
Tag: North America
Number: 5.500000
Nationality: Brazilian
Tag: South America
Number: 1.100000
Nationality: Japanese
Tag: Asia
After sorting:
Number: 1.100000
Nationality: Japanese
Tag: Asia
Number: 3.300000
Nationality: Canadian
Tag: North America
Number: 5.500000
Nationality: Brazilian
Tag: South America