Here is my code for the sorting the list in ascending order. I have used function within the function. Now I want to calculate the Time complexity of this function. From my side I have calculate that the function "unite" is called every time when function "sort" complete its loop. So two functions are used every time in this function. So I have concluded that the Complexity of this function is O(nlog(n)). I am new to this chapter. So I want to know how to calculate this type of complexity. The answer above is just my approximation. And neither I know the real answer nor I have any solution or hints. So please describe your answer whenever you give. Thanks. Here is my code.
def sort(lst):
def unite(l1, l2):
if len(l1) == 0:
return l2
elif len(l2) == 0:
return l1
elif l1[0] < l2[0]:
return [l1[0]] + unite(l1[1:], l2)
else:
return [l2[0]] + unite(l1, l2[1:])
if len(lst) == 0 or len(lst) == 1:
return lst
else:
front = sort(lst[:len(lst)/2])
back = sort(lst[len(lst)/2:])
L = lst[:] # the next 3 questions below refer to this line
return unite(front, back)
First step is to note that the real work is being done in the
unite
step of your code, which doesn^2
work because you're creating new lists every time.So you can actually write a quick recurrence for the amount of work your function is doing:
because you're recursing twice on lists that are of length
n/2
and doingn^2
work to rejoin them.Now, consider a recursion tree - at a certain level of the tree (call it level
i
), you're doing2^i * (n/2^i)^2
work. That's aboutO(n^2)
work at each level, and there'slog(n)
levels, so you're doingO(n^2log(n))
work.However, there is a way to write your
unite
function so it runs much faster, inO(n)
time. In that case, you'd be doing (by a similar analysis as above)O(nlog(n))
work.