【问题标题】:Is counting sort present in std: sort in STL?std中是否存在计数排序:STL中的排序?
【发布时间】:2018-05-06 11:44:43
【问题描述】:

计数排序具有时间复杂度:O(n+k) n-> 输入的大小 k-> abs。差异。 b/w 最小值和最大值。在某些情况下,计数排序优于基于比较的排序算法 它是否存在于 std: 在 STL 中排序?如果没有,有什么原因吗? 还有 STL 中可用的计数排序功能吗?

【问题讨论】:

  • 原则上,没有什么能阻止std::sort 实现检测有利于计数排序的(相当狭窄和专门的)条件,并使用它而不是通用排序算法。我不知道实际上有任何实现。如果我不得不猜测原因,我会怀疑这不值得麻烦 - 计数排序适用的情况在实践中很少见。如果您知道您的算法会从中受益,请随意实现它或查找现有的第三方实现。
  • 我可以确认它不存在于 Visual Studio 的 std::sort() 实现中,它是 introsort 的变体。

标签: sorting stl counting-sort


【解决方案1】:

std 中是否存在计数排序:STL 中的排序?

不,它不存在。 sort 函数基于快速排序和其他启发式方法。

如果没有,有什么原因吗?

可能是因为它很容易实现。检查psuedocode

count = array of k+1 zeros
for x in input do
    count[key(x)] += 1

total = 0
for i in 0, 1, ... k do
    count[i], total = total, count[i] + total

output = array of the same length as input
for x in input do
    output[count[key(x)]] = x
    count[key(x)] += 1 

return output

STL 中还有任何用于计数排序的函数吗?

C++ STL 提供了基本的拟合数据结构——数组和向量,可用于实现计数排序。

map也可以用来实现计数排序,但不会是O(n)了,因为map操作的复杂度是O(logn)。

【讨论】:

    猜你喜欢
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 2018-10-10
    • 2010-11-29
    • 1970-01-01
    • 2013-10-29
    相关资源
    最近更新 更多