【问题标题】:How to find the i-th largest number of a set, and order the i largest numbers如何找到集合的第 i 个最大数,并对 i 个最大数进行排序
【发布时间】:2013-01-19 12:37:50
【问题描述】:

“Cormen Leiserson Rivest Stein,第 3 版,问题 9-1,C 点,第 224 页”,我有以下作业:

给定一组(数组)A n 个数字,使用顺序统计 算法找到 i-th 最大的数,围绕它进行分区 数,然后对 i 个最大的数进行排序。

我使用了 Randomized-Select 算法(来自同一本书,第 216 页 - 它使用 Randomized-Partition 算法)找到第 i 个 smallest 数,而我想找到i-th 最大数(我们称它为“k-th”以避免混淆)。基本上,我可以获得第 k 个最大的数:

n - ith + 1

然后我调用 RandomizedSelect() 来找到第 k 个最大的数字,一切都很好!

这里有一个例子(用 C 语言)我如何找到第 4 大数:

int A[10] = {3, 20, 15, 4, 1, 9, 18, 64, 22, 5}; // the given A set
int ith = 4; // I want to find the 4-th largest number of A
int kth = 10 - ith + 1; // I do this "conversion" for the reasons I explained above
int i = RandomizedSelect(A, 0, 9, kth); // it returns the index of A pointing to the 4-th largest number

printf("A vector: ");
for (j = 0; j < 10; j++) printf ("%u ", A[j]); // prints the A vector partially "ordered"

printf("\n4-th largest number: %u", A[i]); // prints the 4-th largest number

这里有一个输出示例:

一个向量:3 1 4 5 9 15 18 64 22 20

第 4 大数字:18

现在我不仅想要第 4 个最大的数字,还想要其他 4 个最大的数字 S 以有序的方式(来自示例:18 20 22 64)。所以我只是在 A 向量上运行例如 MergeSort(),从之前找到的第 i 个索引开始直到结束。输出将是:18 20 22 64。

问题是作业说我必须围绕第 i (4-th) 个最大数字进行分区,并对其他 i (4) 个最大数字进行排序,然后如前所述运行 MergeSort()。但我不明白我为什么要这样做......在我的例子中,在 18 附近进行分区没有任何意义,因为我尝试过,这已经是我进行分区后 A 向量的输出(调用 SelectedPartition()):

3 1 4 5 9 15 18 64 22 20

18

...输出相同!

那么,我对作业有什么误解?或者,我做得更好吗?

【问题讨论】:

    标签: c algorithm sorting selection


    【解决方案1】:

    有许多不同的算法可用于计算订单统计信息。许多,如快速选择或中位数算法,自动将数组围绕第 k 个元素分区,作为其实现的一部分。但是,不能保证选择算法必须这样做。例如,您可以通过将所有元素放入顺序统计树数据结构中来实现选择,然后查询第 k 个元素。因此,最正确的做法是放入显式分区步骤以确保分区发生。

    在您的情况下,由于您使用的算法已经进行了分区,因此您可以放心地忽略此步骤。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2015-06-02
      • 2011-03-08
      • 1970-01-01
      • 2019-05-31
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多