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.
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?
count[i]times, notktimes.ntimes.