[英]What is k in counting sort O(n+k) time complexity?
Counting sort worst, best and average time complexity is O(n+k)
, where n is number of elements to sort. 计算排序的最差,最佳和平均时间复杂度为O(n+k)
,其中n是要排序的元素数。 What is k exactly? k是多少? I see different definitions: maximum element, difference between max element and min element, and so on. 我看到了不同的定义:最大元素,最大元素和最小元素之间的差异,等等。
arr1 [1, 3, 5, 9, 12, 7 ]
and arr2 [1,2,3,2,1,2,4,1,3,2]
what is k
for arr1
and arr2
? 给定数组arr1 [1, 3, 5, 9, 12, 7 ]
arr2 [1,2,3,2,1,2,4,1,3,2]
和arr2 [1,2,3,2,1,2,4,1,3,2]
对于arr1
和arr2
什么是k
? arr1
with counting sort because n < k
(element values are from a range which is wider than number of elements to sort? 是因为n < k
(元素值的范围大于要排序的元素数的范围),所以用计数排序对arr1
进行排序是愚蠢的吗? k
is the range of the keys, ie the number of array slots it takes to cover all possible values. k
是键的范围,即覆盖所有可能值所需的阵列插槽数。 Thus in case of numbers, Max-Min+1
. 因此,如果是数字, Max-Min+1
。 Of course this assumes that you don't waste space by assigning Min
the first slot and Max
the last. 当然,这假设您没有通过将Min
分配给第一个插槽,将Max
分配给最后一个插槽来浪费空间。
It is appropriate to use counting sort when k
does not exceed a small multiple of n
, let nk
, as in this case, nk
can beat n.log n
. 当k
不超过n
的小倍数时,最好使用计数排序,让nk
n.log n
,因为在这种情况下nk
可以击败n.log n
。
k是数组中的最大可能值,假设您有长度为5的数组,每个数字都是0到9之间的整数,在此示例中,k等于9
First an array of k counts is zeroed. 首先,将k个计数的数组清零。 Then the n elements in the array are read, and the elements of the k counts are incremented depending on the values of the n elements. 然后读取数组中的n个元素,并根据n个元素的值增加k个计数的元素。 On the output pass of a counting sort, the array of k counts is read, and array of n elements is written. 在计数排序的输出通道上,读取k个计数的数组,并写入n个元素的数组。 So there are k writes (to zero the counts), n reads, then k reads and n writes for a total of 2n + 2k operations, but big O ignores the constant 2, so the time complexity is O(n + k). 因此,共有k次写入(计数为零),n次读取,k次读取和n次写入,总共进行2n + 2k次操作,但是大O忽略常数2,因此时间复杂度为O(n + k)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.