c - 从高到低排序输出

标签 c sorting struct

我做了一个简单的程序,它只会将输入显示为输出。 我的主要问题是我想将输出从高到低排序。 输出不是从高到低排序,而是与输入的顺序相同。 谁能检查我的代码,看看为什么它没有排序。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#define size 7
#include<stdlib.h>
struct books
{
    int profit;
};
void load(struct books b[], int n)
{
    int i;
    for (i = 0; i < n; i++)
    {
        printf("Enter profit:\n");
        scanf("%d", &b[i].profit );
    }
}
void print(struct books b[], int n)
{
    int i;
    for (i = 0; i<n; i++)
    {
        printf("Profit is:%d\n",b[i].profit);
    }
}
void sort(struct books b[], int n)
{
    int i; int j;
    books t;
    for (i = 0; i < n-1; i++)
        for (j = 0; j < n-1 ; j++)
            if (b[j].profit < b[j + 1].profit)
            {
                t = b[j];
                b[j] = b[j + 1];
                b[j+1] = t;
            }
}
void main()
{
    books b[size];
    load(b, size);
    print(b, size);
    sort(b, size);
    system("pause");
}

最佳答案

如果要打印排序后的列表,需要先调用sort再调用print:

void main()
{
    books b[size];
    load(b, size);

    sort(b, size);
    print(b, size);

    system("pause");
}

此外,我认为您需要将 books 结构定义为

    struct books b[size];

如果你想避免编译错误。

最后,要从低到高而不是从高到低打印列表,您可以按照另一个答案中的建议修改排序算法,也可以按如下方式修改打印算法:

void print(struct books b[], int n)
{
    int i;
    for (i = n-1; i>0; i--)
    {
        printf("Profit is:%d\n",b[i].profit);
    }
}

关于c - 从高到低排序输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30146986/

相关文章:

c - C 上的初始化结构问题

当定义包含参数时调用不带参数的函数

c - "["标记之前的预期表达式

php - WordPress 对 WP_Query 返回的帖子进行排序

C# struct 在运行时实例化

arrays - 在 swift 5 中过滤结构的嵌套数组

c++ - 为结构体灵活数组赋值

C 使用 strdup() 等从文件中读取/打印单词

javascript - 在 Ember 中按照不同模型的属性进行排序

javascript - 对条件 Array.sort() 的 Jest 覆盖