如何像这样对结构进行排序:
typedef struct
{
int weight;
int price;
Color color;
Equip equip;
}Cars;
通过它的属性之一,如价格或重量?先前声明了 Automobil 数组。 我不能使用指针和任何其他内置函数。
Cars automobil[5];
Cars mobilOne={};
for(i=0; i<5; i++)
{
if((i+1)==5)
{
break;
}else
{
if (automobil[i].weight> automobil[i+1].weight)
{
mobilOne = automobil[i];
automobil[i] = automobil[i+1];
automobil[i+1] = mobilOne;
}
}
}
我试过用这种方式做这个,但它没有做任何事情...... 另外,如果有人能告诉我,如何将这样的结构传递给函数,我将非常感激!
最佳答案
好的,首先,您尝试做的事情并不像某些人可能告诉您的那样糟糕,因为小 N 冒泡排序仍然非常快。以下将为您完成,当然您需要一个双循环:
int main() {
Cars automobil[NC];
// Initialiase automobil here
for (int i = 0; i < NC - 1; ++i) {
int am = i;
for (int j = i+1; j < NC; ++j) {
if ( automobil[am].weight > automobil[j].weight )
am = j;
}
if ( am != i) {
Cars tmp = automobil[am];
automobil[am] = automobil[i];
automobil[i] = tmp;
}
}
for (int i = 0; i < NC; ++i)
printf("%d\n", automobil[i].weight);
}
请注意,我们可以复制结构,但即使在这里我们也尽量少做。
但是,很容易说“我永远不会拥有超过 10 辆汽车”,然后发现您正在尝试对几千辆汽车进行排序,所以我建议您学习和理解 qsort():
int carsSort(const void *a, const void *b) {
return ((Cars *) a)->weight - ((Cars *) b)->weight;
}
int main() {
Cars automobil[NC];
// Initialiase automobil here
qsort(automobil, NC, sizeof *automobil, carsSort);
for (int i = 0; i < NC; ++i)
printf("%d\n", automobil[i].weight);
}
约翰
PS:回复“如何将数组传递给函数?”记住 K&R 的一句名言:“当将数组名传递给函数时,传递的是数组开头的位置”。
因此:
int carsSort(const void *a, const void *b) {
return ((Cars *) a)->weight - ((Cars *) b)->weight;
}
void sortThem(Cars autom[]) {
qsort(autom, NC, sizeof *autom, carsSort);
}
int main() {
Cars automobil[NC];
// Initialiase automobil here
sortThem(automobil);
for (int i = 0; i < NC; ++i)
printf("%d\n", automobil[i].weight);
}
在 sortThem() 内部,“autom”是一个变量,其值为 automobil[0] 的地址。
关于C:如何按其元素之一对结构进行排序?不能使用指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46647720/