如果我有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,我觉得这需要太长时间,必须有一个更有效的方式
答案 0 :(得分:1)
您可以使用 marker (interface) design pattern 解决此问题 通过在每次获得最大值时保留数组中访问索引的记录,让我先定义解决方案结构然后逐步完成它:
score_list
大小相同的新数组,让我们调用该数组marker
示例运行
在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);
}