CSA Lab 3
CSA Lab 3
CSA Lab 3
LAB # 03
Algorithm Complexity
OBJECTIVE
To calculate the Time Complexity to identify the best algorithm with Big.O Asymptotic Notation
THEORY
Algorithm Complexity:
Algorithm complexity is a measure which evaluates the order of the count of operations, performed by a
given or algorithm as a function of the size of the input data. To put this simpler, complexity is a rough
approximation of the number of steps necessary to execute an algorithm. When we evaluate complexity we
speak of order of operation count, not of their exact count .
For example: if we have an order of N2 operations to process N elements, then N 2/2 and 3*N2 are of one and
the same quadratic order.
Asymptotic Notations:
Asymptotic Notations are languages that allow us to analyze an algorithm’s running time by identifying its
behavior as the input size for the algorithm increases .
Complexity can be constant, logarithmic, linear, n*log(n), quadratic, cubic, exponential, etc. This is
respectively the order of constant, logarithmic, linear and so on, number of steps, are executed to solve a
given problem. For simplicity, sometime instead of “algorithms complexity” or just “complexity” we use
the term “running time”.
Big-Omega:
Big-Omega, commonly written as Ω, is an Asymptotic Notation for the best case, or a floor growth rate for a
given function. It provides us with an asymptotic lower bound for the growth rate of the runtime of an
algorithm.
f(n) is Ω(g(n)), if for some real constants c (c > 0) and n 0 (n0 > 0), f(n) is >= c g(n) for every input
size n (n > n0).
EXERCISE:
A. Create a file named lab3.py. Write the name of the complexity of the following codes w.r.t Big O
notation
1. Code:
def multiply(items): ANSWER:-
result = items[0] * items[0] THIS IS LINEAR NOTATION
print (result)
multiply([4, 5, 6, 8])
2. Code:
def code_2(items):
for item in items:
for item2 in
items:
print(item, ' ' ,item)
code_2 ([4, 5, 6, 8])
ANSWER:-
THIS IS QUADRATIC NOTATION.
B. Assume ( )= 2n3 - 5n2 +10n+1, determine the value of big o notation (upper bound)
SOLUTION:
2n3 - 5n2 + 10n + 1 ≤ 8n3
For n = 1
2(1)3 - 5(1)2 + 10(1) + 1 ≤ 8(1)3
2 – 5 + 10 + 1 ≤ 8
8 ≤ 8
For n = 2
2(2)3 - 5(2)2 + 10(2) + 1 ≤ 8(2)3
2(8) – 5(4) + 10(2) + 1 ≤ 8(8)
16 – 20 + 20 +1 ≤ 64
17 ≤ 64
For n = 3
2(3)3 - 5(3)2 + 10(3) + 1 ≤ 8(3)3
2(27) – 5(9) + 10(3) + 1 ≤ 8(27)
54 – 45 + 30 +1 ≤ 216
40 ≤ 216
Hence C = 8
g(n) = g(n3)
B. Assume ( )= 5n4 + 3n3 + 2n2 + 4n + 1, determine the value of big o notation(upper bound)
SOLUTION:
5n4 + 3n3 + 2n2 + 4n + 1 ≤ 15n4
For n = 1
5(1)4 + 3(1)3 + 2(1)2 + 4(1) + 1 ≤ 15(1)4
5 + 3 + 2 + 4 + 1 ≤ 15
15 ≤ 15
For n = 2
5(2)4 + 3(2)3 + 2(2)2 + 4(2) + 1 ≤ 15(2)4
5(16) + 3(8) + 2(4) + 4(2) + 1 ≤ 15(16)
80 + 24 + 8 + 8 + 1 ≤ 240
121 ≤ 240
For n = 3
5(3)4 + 3(3)3 + 2(3)2 + 4(3) + 1 ≤ 15(3)4
For i in n: 1 n n
For j in n: 1 n*n n2