0

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?

7
  • The inner loop (comprehension) increases your complexity from k to n because it expands the non-singular elements Commented Apr 25, 2019 at 17:59
  • No, because the inner loop only loops count[i] times, not k times. Commented Apr 25, 2019 at 17:59
  • SUM(count[i]) == len(array) Commented Apr 25, 2019 at 18:00
  • If there's only a single repeating element, the inner loop would only execute once. In the end, your loops are always performing "add an element to the array" exactly n times. Commented Apr 25, 2019 at 18:02
  • @Blorgbeard would that mean that worst case is n+k, or 2n? Commented Apr 25, 2019 at 18:08

1 Answer 1

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:

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

is count[i], and the sum of all count[i] is equal to n. Note that the comparison

        if count[i] != 0:

is done k times, and in the worst case scenario the

sorted +=...

is also done k-times. Adding all this up you get your 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).

Sign up to request clarification or add additional context in comments.

5 Comments

So the list comprehension will run max n times, with the comparison running k times, wouldnt that make it n*k?
No, because the list comprehension cannot run n times for every k. the total sum of list comprehension iterations is equal to the sum of count[i] which is exactly n.
For example if you have an iteration where the list comprehension is of size n, then for all other iterations, the list comprehension is of size 0 (this only happens when all entries in the array have the same value).
Gotcha, but if the list comprehension runs n times it would have O(n) and taking into account the first for loop it would give O(n+n)?
In part, but you would still have k comparisons even if you are not in the worst case scenario.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.