Data Structures & Algorithms - Topic 3 - Time Complexity Basics
Data Structures & Algorithms - Topic 3 - Time Complexity Basics
ALGORITHMS
A() A(n)
{ {
For j = 1 to n If (-----)
Print “Hello” A(n/2)
}
}
Time Complexity (Iterations)
For i=1 to n T(n)=n
<computational instruction>
=O(n)
-----------------------------------------------------------
For i=1 to n
For j=1 to n
T(n)=n.n=n 2
=O(n )
<computational instruction>
2
i 1 2 3 4 5 6 7 … n
J n n n n n n n … n
Time Complexity (Iterations)
For i=1 to n
T(n)=n.n.n=n 3
For j=1 to n
For k=1 to n
=O(n )
3
<computational instruction>
----------------------------------------------------------------
For i=1 to n
For j=1 to n
T(n)=n.n.n.n=n
For k=1 to n =O(n )
4
For l=1 to n
<computational instruction>
Time Complexity (Iterations)
T(n)=O() i <=n
2
i<=
Time Complexity (Iterations)
T(n)=100+200+…+n.10
=100(1+2+…+n)
For i=1 to n =100.n(n+1)/2
For j=1 to i
=O(n2)
For k=1 to 100
<computational
instruction>
i 1 2 3 4 … n
j 1 times 2 times 3 times 4 times … n times
k 1x100 2x100 3x100 4x100 … nx100
times times times times times
Things to remember
Sum of squares of 1st m natural numbers=m(m+1)(2m+1
<computational instruction> Or
k=log2n
T(n)=O(logmn)
Time Complexity (Iterations)
T(n)=(+1)(n/2)O(lg n)
For i=n/2 to n
For j=1 to n/2 =O(n 2
.lg n)
For k=1 to n & k=k*2
<computational instruction>
-----------------------------------------------------------
For i=n/2 to n T(n)=(+1).O(lg n).O(lg n
For j=1 to n & j=2*j
=O(n.(lg n)2)
For k=1 to n & k=k*2
<computational instruction>
Time Complexity (Iterations)
While(n>1)
n=n/2
T(n)=O(log 2 n)
<computational instruction>
i = 1 to n i = n to 1
←same→
i=i*2 i=i/2
where = 0.5772156649…
i 1 2 3 … n
j n times n/2 n/3 … n/n
times times times
Iterative vs. Recursive Time
A() A(n)
{ {
For j = 1 to n If (-----)
Print “Hello” A(n/2)
}
}
Recursions
■ A function calls itself repeatedly
c c
c
c Algo(1)
22
Recursion Tree Method
■ Let’s consider another example:
T(n) = T(n-1)+n, for n>1
T(1) = n This is the Anchor Condition
-------------------------------------------------------------------------
Note that here, at each step, only 1 branches will be
drawn; decreasing the input size by 1 at each step.
And a total of n work will be done at branching.
23
T(n n
)
T(n- n-1
1)
Recursive
Relations
Back Recursion
Master
Substituti Tree
Theorem
on Method Method
25
Master Theorem
■The master theorem provides a solution in
asymptotic terms (using notation) for
recurrence relations of types that occur in the
analysis of many divide and conquer algorithms.
■The function must be in some specific pattern.
■Not all the problems can be solved by Master
Theorem.
■It has various versions; we will use an easy one.
26
Master Theorem
■ Function Pattern:
THANK YOU