【问题标题】:C programming: Sorting a integer file while keeping their original place in fileC 编程:对整数文件进行排序,同时保留它们在文件中的原始位置
【发布时间】:2015-02-26 16:27:53
【问题描述】:

好的,这里我有一个小函数,可以对程序中写的一些值进行排序

 #include <stdio.h>      /* printf */
 #include <stdlib.h>     /* qsort */
 #include <conio.h>      /* getch */

 int values[] = { 40, 10, 100, 90, 20, 25 };

 int compare (const void * a, const void * b)
 {
     return ( *(int*)a - *(int*)b );
 }

 int main ()
 {
      int n;
      qsort (values, 6, sizeof(int), compare);
      for (n=0; n<6; n++)
      printf ("%d ",values[n]);
      getch();
}

这很好用,没有给出错误。

现在,在我的主项目中,我必须对文件中的值进行排序。我在想我可以从文件中复制这些值并执行与此处完全相同的操作。

然而,这似乎很容易,但我还需要他们在文件中的行,这意味着我需要第二个数组,其中包含数字 1-SIZE。鉴于我的文件应最大为 512 行。我可以采取哪些步骤来完成这项工作?

例子:

User ID:              Score:
1                     13
2                     9
3                     13
4                     19
5                     8
6                     11
7                     14
8                     17

应该改成

User ID:             Score:                  
5                    8
2                    9
6                    11
3                    13
1                    13
7                    14
8                    17
4                    19

【问题讨论】:

  • 读取字符串向量中的所有行(即char**),然后创建一个比较函数,根据字符串中的第二个整数比较两个字符串。
  • 使用两个整数的结构,并根据结构进行比较。
  • @MihaiMaruseac 当然,我该怎么做?
  • 已经提供的答案是否不能回答您的问题?
  • @ryyker 是的,它工作得很好。

标签: c arrays file sorting


【解决方案1】:

这是你需要的

 #include <stdio.h>      /* printf */
 #include <stdlib.h>     /* qsort */

struct Element
{
    int userId;
    int score;
};

struct Element elements[] = { 
    {1, 13},
    {2,  9},
    {3, 13},
    {4, 19},
    {5,  8},
    {6, 11},
    {7, 14},
    {8, 17},
};

int ascendingSortCompareFunction (const void * a, const void * b)
{
    return (((struct Element *)a)->score - ((struct Element *)b)->score);
}

int descendingSortCompareFunction (const void * a, const void * b)
{
    return ((struct Element *)b)->score) - (((struct Element *)a)->score;
}

int main ()
{
    int n;
    int count;

    count = sizeof(elements) / sizeof(elements[0]);

    qsort(elements, count, sizeof(elements[0]), ascendingSortCompareFunction);
    printf ("UserID\tScore (Ascending Sort)\n");
    for (n = 0 ; n < count ; n++)
        printf ("%d\t%d\n", elements[n].userId, elements[n].score);

    qsort(elements, count, sizeof(elements[0]), descendingSortCompareFunction);
    printf ("UserID\tScore (Descending Sort)\n");
    for (n = 0 ; n < count ; n++)
        printf ("%d\t%d\n", elements[n].userId, elements[n].score);

    getchar();

    return 0;
}

【讨论】:

  • 谢谢!,它工作得很好。有没有可以按降序排序的快速修复方法?
  • @ThatBlueJuice 你可以有两个compare 函数。只是。你是新来的,你读过this吗。
  • 是的,除了我应该改变一个或另一个,我只是问我应该使用哪一个。
  • @ThatBlueJuice 如果它真的有帮助,请接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-09
  • 1970-01-01
  • 2019-10-19
  • 2011-11-04
  • 1970-01-01
  • 1970-01-01
  • 2017-07-12
相关资源
最近更新 更多