-
Notifications
You must be signed in to change notification settings - Fork 0
/
Complexity Code
51 lines (35 loc) · 2.18 KB
/
Complexity Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#BigO time complexity O(1)
def BigO2(a):
print(a+a) #this function will run only 1 time so the the time complexity for this will be O(1)
Big01(10) #although we are performing addition over here but, as we neglect the constant, hence complexity will be O(1)
#BigO time complexity O(n)
def BigO2(a):
for i in range(a): #this function will run 'a' times so the the time complexity for this will be O(n)
print(i)
Big02(10)
#BigO time complexity O(n+n)
def BigO3(a):
for i in range(a): #this function will run 'a' times so the the time complexity for this will be O(n)
print(i)
for i in range(a): #this function will run 'a' times so the the time complexity for this will be O(n)
print(i)
BigO3(10) #Final complexity will be O(n + n) => O(2n) => O(n) , as we neglect the constant while calculating the complexity
#BigO time complexity O(n^2)
def BigO4(a):
for i in range(a): #this function will run 'a' times so the the time complexity for this will be O(n)
for j in range(a): #this function will run 'a' times so the the time complexity for this will be O(n)
print(i,j)
BigO4(10) #Final complexity will be O(n * n) => O(n^2)
#BigO time complexity O(n^3)
def BigO5(a):
for i in range(a): #this function will run 'a' times so the the time complexity for this will be O(n)
for j in range(a): #this function will run 'a' times so the the time complexity for this will be O(n)
for l in range(a): #this function will run 'a' times so the the time complexity for this will be O(n)
print(i,j,l)
BigO5(10) #Final complexity will be O(n * n * n) => O(n^3)
#BigO time complexity O(log n)
'''Suppose you have to find an element(i.e. 34) in a sorted array arr[1,4,15,22,34].
Now if we go by a normal method of finding an element in a linear sequence then we need to run the loop 5 times (i.e size of arr).
If i go by binary search algorithm i only need to run the loop for finding the element thrice.
So, the complexity will be O(log n).
I will explain this in detail when we will learn more about Binary search algorithm.'''