【问题标题】:Sorting output from high to low输出从高到低排序
【发布时间】:2015-05-10 02:10:35
【问题描述】:

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

#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");
}

【问题讨论】:

  • 你的意思是和输入一样的order,不一样的format
  • 在 main() 中打印后调用 sort
  • @b0fh 感谢您的回答帮助!

标签: c sorting struct


【解决方案1】:

如果要打印排序后的列表,需要在调用 print 之前调用 sort:

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);
    }
}

【讨论】:

    【解决方案2】:

    使用这样的东西(倒置冒泡排序):

    void inverted_sort(books b[], int size){
        int profit;
        bool swap;
    
        do{
            swap = false;
            for (int i= 0; i < (size - 1); i++){
                if (b[i].profit < b[i + 1].profit){
                    profit = b[i].profit;
                    b[i].profit = b[i + 1].profit;
                    b[i + 1].profit = profit;
                    swap = true;
                }
            }
    
        } while (swap);
    }
    

    记得更改函数顺序,inverted_sort() 必须在 print() 之前。

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

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      使用这个:

      void sort(struct books b[], int n)
      {
          int i; int j;
          books t;
          for (i = 0; i < n; i++)
              for (j = i + 1; j < n ; j++)
                  if (b[j].profit > b[i].profit)
                  {
                      t = b[j];
                      b[j] = b[i];
                      b[i] = t;
                  }
      }
      

      【讨论】:

        猜你喜欢
        • 2020-08-10
        • 1970-01-01
        • 2020-11-12
        • 2017-02-06
        • 1970-01-01
        • 1970-01-01
        • 2015-04-13
        • 1970-01-01
        • 2021-07-16
        相关资源
        最近更新 更多