algorithm - 部分排序以找到第 k 个最大/最小元素

标签 algorithm sorting heap selection

来源:Wikipedia

A streaming, single-pass partial sort is also possible using heaps or other priority queue data structures. First, insert the first k elements of the input into the structure. Then make one pass over the remaining elements, add each to the structure in turn, and remove the largest element. Each insertion operation also takes O(log k) time, resulting in O(n log k) time overall.

  1. 这与我们首先在 O(n) 时间内堆化完整的输入数组然后提取堆中的最小值 k 次的情况有何不同。
  2. 我不明白它说遍历剩余元素,依次将每个元素添加到结构中,然后删除最大元素 的部分。这不是和1)中描述的方法一样吗?

最佳答案

建议的方法是流式传输。考虑到 O(k) 空间复杂度(但它只会找到前 k 个项目),它不需要内存中的所有项目来运行 heapify 算法。

算法的更明确的描述(另请参阅 WP 给出的 reference)是

  • 给定一个项目流:
  • 将流中的前 k 个元素堆成一个堆,
  • 对于第一个 k 之后的每个元素:
    • 将其压入堆中,
    • 从堆中取出最大(或最小)的元素并丢弃,
  • 最后返回堆中剩余的 k 个值。

通过构建,堆永远不会增长到超过 k + 1 个元素。这些项目可以从磁盘、网络等流式传输,这对于 heapify 算法是不可能的。

关于algorithm - 部分排序以找到第 k 个最大/最小元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24407555/

相关文章:

algorithm - 根据样本运行估算模拟运行时间

php - 按照其他数组定义的顺序对数组进行排序

memory-management - 动态堆分配困惑

java - 优先级队列中的已排序与未排序数据 为什么自动排序和排序会等待?

algorithm - 壳牌比。希伯德时间复杂度比较

java - 是否可以用堆实现最小优先级队列,或者是否需要二叉堆?

algorithm - 元组数据集的二元分类

计算一组正整数的 Frobenius 数的算法

algorithm - 形成三角形

ruby-on-rails - will_paginate 和 .sort =>