简体   繁体   English

此实现计数排序的时间复杂度

[英]Time complexity of this implementation of counting sort

I have to determine the time complexity for the given code of counting sort. 我必须确定给定计数排序代码的时间复杂度。 I know that counting sort should be O(n+k) but I just can't see how this function is O(n+k), seeing as there is a for loop inside the second for loop. 我知道计数排序应该是O(n + k),但是我看不到这个函数是O(n + k),因为第二个for循环中有一个for循环。

def counting_sort(array, k): # k is max(array)

    count = (k+1) * [0]  
    sorted = []
    for i in array:
        count[i] += 1
    for i in range(len(count)):
        if count[i] != 0:
            sorted += [i for j in range(count[i])]
    return sorted

Wouldn't the worst case be n+k^2, if the elements are unique? 如果元素是唯一的,最坏的情况不是n + k ^ 2吗?

The first loop 第一个循环

for i in array:
    count[i] += 1

takes n iterations, for the second loop the number of instructions executed in the worst case scenario for the list comprehension: 进行n次迭代,在第二个循环中,对于列表理解,在最坏情况下执行的指令数:

i for j in range(count[i]) #

is count[i] , and the sum of all count[i] is equal to n. count[i] ,并且所有count[i]的总和等于n。 Note that the comparison 注意比较

        if count[i] != 0:

is done k times, and in the worst case scenario the 完成了k次,在最坏的情况下,

sorted +=...

is also done k-times. 也做了k次。 Adding all this up you get your O(n+k) 将所有这些加起来,就可以得到O(n + k)

(assuming the += for sorted is constant cost, otherwise we have to say that the += is amortized constant and so the result comes with that caveat). (假设用于sorted的+ =是常数成本,否则我们必须说+ =是摊销常数,因此结果带有警告性)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM