【问题标题】:C int array sortC int 数组排序
【发布时间】:2014-11-23 23:25:40
【问题描述】:

如果我有一个像这样的int[3] 数组:

score_list[3] = [ 1, 2, 0]

数组中的每个位置对应一个特定的文档编号:

score_list[0] = D1
score_list[1] = D2
score_list[2] = D3

按降序对数组进行排序的最简单方法是什么,跟踪每个移动的 int 的位置

在哪里(排序后):

score_list[3] = [ 2, 1, 0]

score_list[0] = D2
score_list[1] = D1
score_list[2] = D3 

我只需要按降序打印,实际上不需要重新排列int数组,所以:

for (int i=0; i<3; i++)
{
    if (score_list[0] > score_list[1] && score_list[2])
        printf("D%d-%d",i, score_list[0]);
    if (score_list[1] > score_list[0] && score_list[2])
        printf("D%d-%d", i, score_list[1]);
    if (score_list[2] > score_list[0] && score_list[1])
        printf("D%d-%d", i, score_list[2]);
}

会先打印最大的数字,然后我会比较最后2个,我只是觉得这太耗时了,必须有更有效的方法

【问题讨论】:

  • 请描述你尝试了什么。
  • 我不明白你在数组中存储了什么?值还是字符串?或者两者有什么关系?
  • 根据问题是一个int数组
  • 我不明白你想做什么?您需要打印排序后的数组而不更改它吗?
  • 是的,数组是在哈希表中跟踪文档分数的一种更简单的约定,我唯一的问题是按分数降序打印文档

标签: c arrays sorting int


【解决方案1】:

您可以使用 marker (interface) design pattern 解决此问题。
通过每次获得最大值时在数组中记录访问过的索引,让我先定义解决方案结构,然后我将逐步介绍它:

  1. 创建一个与score_list 大小相同的新数组,我们称该数组为marker
  2. 在 for 循环中,您将创建另一个循环来检查最大分数,同时检查标记数组中最大分数的位置是否为 0。

示例运行:
i=0
在 score_list 上循环,找到标记 == 0 的最大分数,打印它,然后为该分数 = 1 放置标记。
i=1
您将执行相同的操作,但现在列表中排除了一个位置

这里有一个示例代码:
请注意:此代码不是可运行的(也没有优化过 O(n^2)),我写它只是为了解释的目的。

int max = -1;
int doc = -1; 
int marker[3] = {0, 0, 0};
for (i=0; i<3; i++)
{
    max = -1;
    for (j=0; j<3; j++)
    {
        // skip this location if it is already printed
        if (marker[j] == 1)
            continue;

        if (score_list[j] > max)
        {
            doc = j;
            max = score_list[j];
        }   
    }

    // this doc will not appear again in the inner for loop (j-loop)
    marker[doc] = 1;

    // print the document with the score
    printf("D%d-%d",doc, max);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 2017-02-17
    • 2023-01-20
    • 1970-01-01
    • 2012-10-23
    • 2021-12-11
    相关资源
    最近更新 更多