This week we start to learn the interesting and harder staff-----Time Complexity.
I will give a simple linear search python function to talk about the time complexity.
ex:
def LS(A,x):
'''Return an index i such that x==L[i]. Otherwise, return -1.'''
i=0 (Line 1)
while i<len(A): (Line 2)
if A[i]==x: (Line 3)
return i (Line 4)
i=i+1 (Line 5)
return -1 (Line 6)
so, if we give an input (A=[2,4,6,8], x=4), what will the time complexity be:
we can trace our code like this:
Line 1: 1 step (i=0)
Line 2: 1 step (0<4)
Line 3: 1 step (A[0]==4)
Line 5: 1 step (i=1)
then again, we go to while loop
Line 2: 1 step (1<4)
Line 3:1 step (A[1]==4)
Line 4: 1 step ( return 1)
so our python function ends here, if we count the total time complexity, it will be 1+1+1+1+1+1+1=7 steps
We can even turn this question into a harder question: what is the worst case in which x isn't in A?
then we can think like this :
line 1 : 1 step (i=0)
while loop : 3* n (line 2,3,5 executes once for each 0 to len(A)-1 , which line 2,3,5 executes once for n times)
then we have 2 more steps to add, which is last while loop check and the last line 'return -1')
so in worst case, the time complexity is 3n+1.
No comments:
Post a Comment