C:如何按其元素之一对结构进行排序?不能使用指针

标签 c function sorting struct

如何像这样对结构进行排序:

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/

相关文章:

c++ - C 中的链接器错误 : undefined Reference to "method" c

即使通过简单的方法也无法在 string 和指定的 char 中找到空格

c - 如何在 C 中合并和排序两个双向链表

iphone - iOS 将输出浮点参数传递给函数

c++ - 在 Map c++​​ 中对 vector 进行排序

c - 未定义对 `SHA1' 的引用

C++ 重载解析、用户定义转换和函数模板

c - struct dirent **foo 到函数

c - 选择排序与链表的

python - 按数组python中的字典值排序